我试图了解我的代码是否正确。我需要声明一个指向结构的指针数组,创建一个新结构并分配值并打印它们。在我看来,我没有正确声明指针数组。我需要知道我做错了什么。谢谢
我收到此编译错误:错误:'people' 未声明(首次在此函数中使用)
我尝试插入 struct data *list;进入 main 但它不起作用
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);
}
既然你想要数组,你需要declare arrays:
char *book[] = { "x", "y", "z",};
int number[] = { 1, 2, 3};
另一个问题是
list = (struct data*) malloc( sizeof(struct data) );
//assigning arguments
list[count]->bookname = ...
Here, list
总是只有一个元素。因此,如果count
除了0
,您将访问数组越界!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)