结构指针数组
我想知道我的代码是否正确。 我需要声明一个指向结构的指针数组,创建一个新的结构并分配值并打印它们。 在我看来,我没有正确地声明指针数组。 我需要知道我做错了什么。 谢谢我收到这个编译错误:错误:’people’未声明(首次在此函数中使用)我试图插入struct data * list; 进入主要但它不会工作
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 bookname, list[i]->booknumber); }
请更改以下代码
// 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]
至
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) );
由于您需要数组,因此需要声明数组:
char *book[] = { "x", "y", "z",}; int number[] = { 1, 2, 3};
另一个问题是
list = (struct data*) malloc( sizeof(struct data) ); //assigning arguments list[count]->bookname = ...
这里, list
总是只有一个元素。 因此,如果count
不是0
,那么你将访问一个超出界限的数组!
我想你应该写:
char *book[] = { "x", "y", "z"};
因为在你的情况下,你正在声明一个字符数组并用指针填充它,这实际上是没有意义的。
在上面的代码行中,它只是意味着“声明一个指针数组”。
希望它有所帮助……
这些都是你的程序中的错误
struct data = { char *bookname; int booknumber;};
“=”不应该在那里
list = (struct data*) malloc( sizeof(struct data) ); list[count]->bookname = x; list[count]->booknumber = y;
在这里你要为单个列表创建空间,所以你不能列出[count] – > bookname,它应该是list-> bookname。 与booknumber相同
并且列表是本地function,您无法在主要访问它。