array of pointers to structures
27,776
Solution 1
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) );
Solution 2
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!
Author by
Jack Morton
Updated on August 01, 2022Comments
-
Jack Morton almost 2 years
I'm trying to understand if my code is correct. I need to declare an array of pointers to structs, create a new struct and assign the values and print them. It seems to me that I'm not declaring array of pointers correctly. I need to know what I'm doing wrong. Thank you I'm getting this compile error: error: 'people' undeclared (first use in this function) And I've tried to insert struct data *list; into main but it wouldnt work
char *book[] = { "x", "y", "z",}; int number[] = { 1, 2, 3}; struct data = { char *bookname; int booknumber;}; function(char *x, int y) { static int count; struct data *list[3]; //creating a new struct list[count] = (struct data*) malloc( sizeof(struct data) ); //assigning arguments list->bookname = x; list->booknumber = y; count++; } int main() { struct data *list[3]; int i; for(i = 0; i < 3; i++) { function(book[i], number[i]); printf("name: %c number: %d", list[i]->bookname, list[i]->booknumber); }
-
Jack Morton almost 12 yearsoff course, i just mistyped it. i ahve arrays in my actual program
-
Jack Morton almost 12 yearswell, i have tried doing struct data *list[3]; but it wouldnt compile
-
chrisaycock almost 12 years@JackMorton Make it a dynamic array:
malloc( sizeof(struct data) * 3 )
-
Jack Morton almost 12 yearsI'm sorry, 1st one is just a mistype again for me. it's in proper shape in the actual code
-
Kevin Vermeer almost 12 yearsThe
[100]
limit is a regression. This should also be dynamically allocated, or handled by the caller. -
Jay almost 12 years@Kevin, The answer is just a sample. So, I have used 100. I have just given him a pointer as to what was causing him the so called compilation error. Hope this clears the air.