views:

68

answers:

2

Transitioning from C++, I am now learning the dark art of C and have developed the following code to replace my need for templating. In the bottom example, I have implemented your garden-variety Node structure in such a way that it can be used to store any data type. Consider the following...

// vptr.c
#include <stdio.h>

struct Node
{  
    void* data;
    struct Node* next;
};

int main()
{  
    struct Node n0, n1;

    n0.next = &n1;
    n0.data = malloc(sizeof(int));

    *((int*) n0.data) = 3;

    printf("%d\n",  *((int*) n0.data));

    return 0;
}

Again, the issue lies with warning free compilation of this code--namely using the gcc compiler, though my wxDevCpp for Windows also gives me some warnings but is much less fussy about it. I blame it on the GUI.

Any help would be greatly appreciated.

+2  A: 

For me, just adding the correct include for malloc (<stdlib.h>) makes your code compile warning free with: gcc -std=c89 -Wall -Wextra -pedantic.

Charles Bailey
+2  A: 

malloc is declared in stdlib.h, which you did not include. So if you add the #include, the warning goes away.

The other warning is about // which is not a valid comment in C89. To make that warning go away use /* */ for comments or tell gcc to use C99.

sepp2k
thanks guys. i was so proud of my syntax, now i feel retarde ;P
Chace Burke
I would say "declared in" instead of "defined in", and declaration is what that matters to the user programmer.
ArunSaha
@Arun: Yes, you're completely right. Fixed it.
sepp2k