Skip to main content

Thread: initializing a structure pointer outside main or a function


here small code .it not working code features can compile understand question.

code:
#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;  }
when compiled above code got following error

code:
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
now came following solutions

1) initializing of structure pointers did above wrong , should done in main() or in function definition.

2) replace
code:
struct node * list,*root;  list=null;  root=null;
by following lines

code:
struct node *list=null;   , struct node *root=null
and compile not error.
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.

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;
while in cases unavoidable, discouraged use global variables. if variable global specific file should use 'static' keyword.


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk initializing a structure pointer outside main or a function


Ubuntu

Comments

Popular posts from this blog

How to change text Component easybook reloaded *newbee* - Joomla! Forum - community, help and support

After Effect warning: A problem occurred when processing OpenGL commands

Preconditions Failed. - Joomla! Forum - community, help and support