I've begun studying data structures, and the linked list popped up. The idea behind a linked list is simple, but the implementation (I use c++) is a bit confusing, especially regarding the nodes used in linked lists. The way a node is defined for a singly linked list in C++ is as follows
// A linked list node
struct Node {
int data;
struct Node* next;
};
or if we were using classes, then it is defined like this.
class Node {
public:
int data;
Node* next;
};
My confusion arises here. How can one define another struct inside struct Node with the same name? I see that the new struct is a pointer to a node, but how does this implementation actually work? It's really confusing :(
How can one define another struct inside struct Node with the same name?
That's not what's happening. You can omit the struct keyword in the data member declaration struct Node* next; such that it might be easier to digest:
struct Node {
int data;
Node* next;
};
Except access specifier (the public), this is now identical to the class version, and it can become clear that you don't define a new struct Node inside of Node, but instead you declare a data member next that is a pointer to an instance of type Node. A pointer on a 64bit machine will need 64bit, that's why the compiler can work with this definition of Node, as the size it must reserve for Node instances is known.
To declare a pointer to something you do not need definition of the class, only its declaration. Therefore this is not recursive definition and the compiler won't run into problems.
You can think of it this way: The pointer member will be the same size whatever the type of the pointer, it still needs only the capacity to address a place anywhere in memory.
Related
I have a struct with cJSON pointers as in:
struct {
cJSON *myJSON1;
cJSON *myJSON2;
...
} myStruct;
Somewhere in my code I create cJSON items as in myStruct.myJSON1 = cJSON_CreateObject()
At the end of the code, I want to call cJSON_Delete() on those pointers which were assigned. I presume this is the classic C case where there is no way to find out if the pointer was malloced in some way. Of course, I can keep a flag to keep track but I want a simple way. I read...
The cJSON struct is as:
/* The cJSON structure: */
typedef struct cJSON
{
struct cJSON *next;
struct cJSON *prev;
struct cJSON *child;
int type;
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
double valuedouble;
char *string;
} cJSON;
The function cJSON_Invalid() is available. The documentation states "(check with cJSON_IsInvalid): Represents an invalid item that doesn't contain any value. You automatically have this type if you set the item to all zero bytes." Do I have to memset the structure to 0 or just type?
In other words, my question is: What would be the easiest way to check if a cJSON pointer is malloced without creating an additional variable? Perhaps set "type" to zero? I can try such options but I want a definite answer which works in all situations.
If you just have an uninitialized pointer to a cJSON data structure the behavior is undefined.
I.e. for cJSON *myJSON1;
cJSON_Invalid(myJSON1) might return 0 or 1.
And cJSON_Delete(myJSON1) will probably segfault. Or do nothing if you get lucky.
The solution is to always initialize cJSON data structures to NULL.
Then you can just call cJSON_Delete(). If the pointer is still NULL the call will do nothing. If it was set up at some point in your program it will correctly release all the memory.
Since you have a structure of multiple cJSON pointers you can set the entire data structure to 0 using memset.
You can take a look at the source code.
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
{
cJSON *next = NULL;
while (item != NULL)
{
...
}
}
I need to store shared array inside a struct in UPC. Is it possible to do?
Struct fields cannot be shared-qualified, for the same reason they cannot be declared with static or extern - a struct field does not carry independent storage-class information (ie because the fields of a struct are always stored contiguously, and could be used for example to declare a stack variable).
However, a struct may contain an array field, and the struct can then be used to define a shared object, eg:
struct S {
int array[100];
int foo;
};
shared struct S data[THREADS];
...
data[MYTHREAD].array[0] = MYTHREAD;
However note the distribution of data in this example is one struct per thread, the array field is not independently distributed across threads.
A struct may also contain a pointer to a shared array, eg:
#include <upc.h>
struct R {
shared int *sa;
int bar;
};
...
struct R r;
r.sa = upc_all_alloc(THREADS, sizeof(int));
r.sa[MYTHREAD] = MYTHREAD;
in this case the shared array is distributed across threads, but the storage is not embedded in the struct - the struct field is just a pointer-to-shared (and thanks to C rules can be accessed with array syntax).
I'm trying to implement a sorted linked list in Go. And I'm having a hard time coming up with a generic way to make the linked list work with any type that can by compared with itself. Since its a sorted list, I want the 'go compiler' to ensure that the values being inserted into the linked list can be compared.
For example,
import "linkedlist"
type Person struct {
name string
}
func main() {
l := linkedlist.New()
p := Person{"Jay"}
l.insert(p)
}
In the above example, how do I make the compiler ensure that the value 'p' which has type 'Person' can be compared with another value which also has type 'Person'. I want the compiler to catch the error in those situations where the value being inserted is not an appropriate value.
I can do something like this,
import "linkedlist"
type Element interface {
func IsGreater(v Element{}) bool
}
type Person struct {
name string
age int
}
func (p *Person) IsGreater(p1 interface{}) bool {
if ok, v := p1.(Person); ok && p.age > v.age {
return true
}
return false
}
And then, within the "insert" function of the linked list I can use the IsGreater function to decide where to place the Element in the linked list.
My question is...
Is there a better way to do this? Something that is a lot better than the solution above.
I've already gone through sort.Sort and seen how its done in that package. The way its done there is to create a new type for a slice of the type and then make that new type fulfill the sort interface by implementing Len, Less and Swap.
I can probably do the same thing here in my case as well. But having to create a new slice type and then implement a few functions to satisfy an interface, when I'll only be dealing with 2 values of the same type at a time.. seems a bit overkill to me.
Because Golang do not support generics, So all of containers should use interface{} and type assert, I think no better solution for your requirement.
Library functions for this already exist:
http://golang.org/pkg/container/list/
http://golang.org/pkg/container/ring/
You can compare the lists with reflect.DeepEqual.
If you want to implement a linked list that uses type checking, make an embedded struct for the list type MyLinkedList struct { *list.List} and one for the items in the list type Element struct{ *List.Element }. You can then implement all the methods of list.List and over-ride as necessary with your type checks.
I've been trying to wrap my head around the concept of interfaces in Go. Reading this and this helped a lot.
The only thing that makes me uncomfortable is the syntax. Have a look at the example below:
package main
import "fmt"
type Interface interface {
String() string
}
type Implementation int
func (v Implementation) String() string {
return fmt.Sprintf("Hello %d", v)
}
func main() {
var i Interface
impl := Implementation(42)
i = impl
fmt.Println(i.String())
}
My issue is with i = impl. Based on the fact that an interface instance actually holds a pointer reference to the actual data, it would feel more natural for me to do i = &impl. Usually assignment of non-pointer when not using & will make a full memory copy of the data, but when assigning to interfaces this seem to side-step this and instead simply (behind the scenes) assign the pointer to the interface value. Am I right? That is, the data for the int(42) will not be copied in memory?
The data for int(42) will be copied. Try this code:
func main() {
var i Interface
impl := Implementation(42)
i = impl
fmt.Println(i.String())
impl = Implementation(91)
fmt.Println(i.String())
}
(Playground link)
You'll find that the second i.String() still shows 42. Perhaps one of the trickier aspects of Go is that method receivers can be pointers as well.
func (v *Implementation) String() string {
return fmt.Sprintf("Hello %d", *v)
}
// ...
i = &impl
Is what you want if you want the interface to hold a pointer to the original value of impl. "Under the hood" an interface is a struct that either holds a pointer to some data, or the data itself (and some type metadata that we can ignore for our purposes). The data itself is stored if its size is less than or equal to one machine word -- whether it be a pointer, struct, or other value.
Otherwise it will be a pointer to some data, but here's the tricky part: if the type implementing the interface is a struct the pointer will be to a copy of the struct, not the struct assigned to the interface variable itself. Or at least semantically the user can think of it as such, optimizations may allow the value to not be copied until the two diverge (e.g. until you call String or reassign impl).
In short: assigning to an interface can semantically be thought of as a copy of the data that implements the interface. If this is a pointer to a type, it copies the pointer, if it's a big struct, it copies the big struct. The particulars of interfaces using pointers under the hood are for reasons of garbage collection and making sure the stack expands by predictable amounts. As far as the developer is concerned, they should be thought of as semantic copies of the specific instance of the implementing type assigned.
When I was reading about Linked list, I came to know that the structure for linked list as
Struct node{
Struct node *next;
int value;
}
Why is the Struct node *next? Why cant it just be an integer pointer? Like below
Struct node{
int *next;
int value;
}
why can't this hold the next node's address? Can anyone please give me explanation?
That's actually what a pointer (*next) does. It holds the address of something else. The type definition describes what this something else is (in this case struct node). Otherwise the application would not know how many bytes to read and how to interpret the data.
Read more about pointers.
Btw. int *next would hold the address of an integer.
Why is the Struct node *next? Why cant
it just be an integer pointer?
Because then you would be pointing to the address of the next integer. This could be used to retrieve the value of the next int, but nothing more, so from there on onward, you would be stuck.
By linking nodes together, which hold integer values, you can traverse the nodes and retrieve the int values.