tags:

views:

91

answers:

6

I am implementing a queue in C. I have a struct like:

struct Node {
    Node* next;
    Node* previous;
    // data
}

Because next and previous are just pointers, does it make a difference if I use Node* or int*? eg:

struct Node {
    int* next;
    int* previous;
    // data
}
+5  A: 

Using int * is incorrect and results in undefined behavior. You can use either Node * or void *, but if you use any type other than Node *, it's going to require a cast (or implicit conversion, e.g. via an assignment) back to Node * before you can dereference it.

R..
+8  A: 

Not only does it bring clarity to your code (which is important, the larger your project gets), pointer math only works properly if you're doing the math on the correct type. In your instance, adding 1 to a Node* would result in adding sizeof(Node) to the base pointer, which is almost guaranteed not to be == sizeof(int).

For the example you gave, it wouldn't likely matter (but you'll need a cast).. but do yourself a favor and get in the good habit now of using the correct types.

San Jacinto
+4  A: 

Yes it does. Node is not an int (Node will be larger that int), so a pointer to int or a pointer to Node will make a difference.

The MYYN
A: 

When you use int *, You mean that you are pointing to an integer, and when you use Node *, it means you are pointing to a node.

The difference is in size of pointed space by pointer. When its int *, pointer++ will shift pointer by sizeof(int) and when its Node *, pointer++ will shift the pointer by sizeof(Node).

Logan
+2  A: 

Everybody is right about everything.

The key point is that even though you may know that the internal representation of a pointer is an address, regardless of data type, C makes no such assumption.

Including an explicit type allows the compiler to do a better job checking your code.

Of course, you can always cast the pointer to a different type but then you need to used the casted-type in its proper context.

By the way, the strict C I learned (back in the Jurassic age) would not allow your first example (C++ does and so do some modern C compilers). Instead you would have to say

struct Node {
    struct Node* next;
    struct Node* previous;
    // data };
yde
Strange compiler that would require `struct` but allow `//`...
Tyler McHenry
Not strange at all. It's standard C.
R..
@yde: Would be interesting to know what C compilers allow this strange dialect of referring to a `struct` tag without a leading `struct`. This implicit lookup is only defined in C++ and erroneous in standard C.
Jens Gustedt
A: 

If there is

Node * pNode;

the expectation is to be able to write expressions like following without any cast

(*pNode).next = ...
pNode->next = ...
ArunSaha