Warning-free Templating in C
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开发者_StackOverflow 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.
For me, just adding the correct include for malloc (<stdlib.h>
) makes your code compile warning free with: gcc -std=c89 -Wall -Wextra -pedantic
.
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.
精彩评论