array of pointers to structures

橙三吉。 提交于 2019-12-03 16:18:12

Please change the following piece of code

    // declaring array of pointers to structs //         
     struct data *list;         
    //not compiling        
    //struct data *list[3]; ---> There is no problem with this statement.        
   //creating a new struct         
   list = (struct data*) malloc( sizeof(struct data) );  ---> //This statement should compilation error due to declaration of struct data *list[3]

to

struct data *list[100]; //Declare a array of pointer to structures  
//allocate memory for each element in the array
list[count] = (struct data*) malloc( sizeof(struct data) ); 

Since you want arrays, you need to declare arrays:

char *book[] = { "x", "y", "z",};
int number[] = { 1, 2, 3};

Another issue is

list = (struct data*) malloc( sizeof(struct data) );

//assigning arguments
list[count]->bookname = ...

Here, list is always going to have exactly one element. So if count is anything other than 0, you will be accessing an array out of bounds!

I think you should write:

char *book[] = { "x", "y", "z"};

Because in your case you were declaring an array of chars and filling it with pointers, which actually makes no sense.

In the line of code above, it just means "declare an array of pointers".

Hope it helped...

These are things are wrong in your program

struct data = { char *bookname; int booknumber;};

"=" should not be there

list = (struct data*) malloc( sizeof(struct data) );
list[count]->bookname = x;
list[count]->booknumber = y;

Here you are creating space for single list, so you cant do list[count]-> bookname, it should be list->bookname. Same with booknumber
And list is local to function, you cant access it in main.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!