Aillyn
Aillyn

Reputation: 23783

Is there a difference between int* and Type*?

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
}

Upvotes: 3

Views: 248

Answers (6)

Arun
Arun

Reputation: 20383

If there is

Node * pNode;

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

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

Upvotes: 0

David E.
David E.

Reputation: 89

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 };

Upvotes: 2

Logan
Logan

Reputation: 2505

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).

Upvotes: 0

user124493
user124493

Reputation:

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.

Upvotes: 8

miku
miku

Reputation: 188014

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.

Upvotes: 4

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215241

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.

Upvotes: 5

Related Questions