[英]array of pointers to structures
我想了解我的代码是否正确。 我需要声明一个指向结构的指针的数组,创建一个新的结构并分配值并打印它们。 在我看来,我没有正确地声明指针数组。 我需要知道我在做什么错。 谢谢,我得到了这个编译错误:错误:未声明“ people”(此功能首次使用),并且我尝试插入结构数据* 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 < 3; i++)
{
function(book[i], number[i]);
printf("name: %c number: %d", list[i]->bookname, list[i]->booknumber);
}
由于需要数组,因此需要声明数组:
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
以外的任何0
,那么您将超出范围访问数组!
请更改以下代码
// 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"};
因为在您的情况下,您声明了一个char数组,并用指针填充了它,这实际上没有任何意义。
在上面的代码行中,它仅表示“声明指针数组”。
希望能有所帮助...
这些是程序中的错误
struct data = { char *bookname; int booknumber;};
“ =”不应该在那里
list = (struct data*) malloc( sizeof(struct data) );
list[count]->bookname = x;
list[count]->booknumber = y;
在这里,您正在为单个列表创建空间,因此您不能执行list [count]->书名,它应该是list-> bookname。 与书号相同
并且列表是本地功能,您不能在主目录中访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.