Thread: initializing a structure pointer outside main or a function
here small code .it not working code features can compile understand question.
when compiled above code got following errorcode:#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node * list,*root; list=null; root=null; struct node * create_node(int ); int main () { int i,j,choice; printf("enter number root of tree\n"); scanf("%d",&i); printf("give choice 1 enter more numbers 0 quit\n"); scanf("%d",&choice); switch (choice) { case 1:break; case 2:break; } } // end of function main struct node * create_node(int data) { struct node *temp; t emp = (struct node *)malloc(sizeof(struct node)); return temp; }
now came following solutionscode:kbc.c:10: warning: data definition has no type or storage class kbc.c:10: error: conflicting types ‘list’ kbc.c:9: note: previous declaration of ‘list’ here kbc.c:10: warning: initialization makes integer pointer without cast kbc.c:11: warning: data definition has no type or storage class kbc.c:11: error: conflicting types ‘root’ kbc.c:9: note: previous declaration of ‘root’ here kbc.c:11: warning: initialization makes integer pointer without cast
1) initializing of structure pointers did above wrong , should done in main() or in function definition.
2) replace
by following linescode:struct node * list,*root; list=null; root=null;
and compile not error.code:struct node *list=null; , struct node *root=null
want know why these 2 solutions mentioned work , wrong approach giving me error?
because, in global space (outside functions) may not make variable/function declarations. c standard allows assign value in type declaration in global space.
while in cases unavoidable, discouraged use global variables. if variable global specific file should use 'static' keyword.code:#include <stdio.h> int x = 0; /* valid, declare global variable */ x = 1; /* invalid, compiler error */ int main (void) { printf ("%d\n, x); return 0;
Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk initializing a structure pointer outside main or a function
Ubuntu
Comments
Post a Comment