LeviX
LeviX

Reputation: 3167

char* ptr to struct

I've come across some C code that I don't quite understand. The following compiles and runs just fine. 1) Why can I cast a char* to a struct* and 2) is there any advantage to using this idiom instead of a void* ?

struct foo
{
    int a;
    int b;
    char *nextPtr;
};

. . .

// This seems wrong
char *charPtr = NULL;

// Why not
//void *structPtr = NULL;

struct foo *fooPtr;
fooPtr = (struct foo*)charPtr;

// Edit removing the string portion as that's not really the point of the question.

Upvotes: 2

Views: 426

Answers (3)

Mark Nunberg
Mark Nunberg

Reputation: 3691

1) As mentioned, you can cast to any pointer type in C. (C++ may have more complex rules, the details of which I'm not aware)...

2) The benefit of char* vs void* is that you may perform pointer arithmetic on a char* but not on a void*.

The wisdom in performing pointer arithmetic is probably questionable based on the code you've posted, but it's often handy with structures which have variable length 'data'.

Upvotes: 1

David W
David W

Reputation: 10184

I think you're just coming across one of those classic "double-edged swords" of C.

In reality, a pointer is a pointer - just a variable that holds an address. You could, in theory, try to force that pointer to point to anything; a struct, an int, a (fill in the blank). C won't complain when you try to cast a pointer to one thing to a pointer for something else; it figures you know what you're doing. Heaven help you if you don't :)

In reality, yeah, a void * is probably a more apt way to declare a pointer that could point to next to anything, but I'm not sure it makes much difference in operation. Won't swear to that point, as there might be compiler optimizations and such that can take place if the pointer is strongly typed...

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67195

  1. You can convert between pointer types because this is the flexibility the language gives you. However, you should be cautious and know what you are doing or problems are likely.

  2. No. There is an advantage to using the property pointer type so that no conversion is needed. If that isn't possible, it doesn't really matter if you use void*, although it may be slightly more clear to developers reading your code.

Upvotes: 1

Related Questions