【发布时间】:2017-07-30 14:03:56
【问题描述】:
这个程序应该从代码开头的硬编码名称和年龄数组中创建一个包含名称和年龄值的结构体数组。 我被明确要求在主函数中声明数组,然后在插入函数中为其分配内存。该程序编译良好,我应该得到的输出是:
姓名:西蒙
年龄:22
姓名:苏西
年龄:24
姓名:阿尔弗雷德
年龄:106
名称:芯片
年龄:6
等等。等等
但是我得到的输出是这样的:
姓名:西蒙
年龄:22
名称:(空)
年龄:33
姓名:苏西
年龄:24
名称:(空)
年龄:33
姓名:苏西
年龄:24
..... 分段错误。
有的名字出现两次,有的名字为空,输出末尾有段错误。 任何帮助将不胜感激。非常感谢。
#include <stdio.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
/* declare your struct for a person here */
struct person {
char *name;
int age;
};
static void insert(struct person **arr, char *name, int age)
{
//initialise nextfreeplace
static int nextfreeplace = 0;
//allocate memory
arr[nextfreeplace] = malloc (sizeof(struct person));
/* put name and age into the next free place in the array parameter here */
arr[nextfreeplace]->name = name;
arr[nextfreeplace]->age = age;
/* modify nextfreeplace here */
nextfreeplace++;
}
int main(int argc, char **argv)
{
/* declare the people array here */
struct person *people;
for (int i = 0; i < HOW_MANY; i++)
{
insert (&people, names[i], ages[i]);
}
/* print the people array here*/
for (int i = 0; i < HOW_MANY; i++)
{
printf("Name: %s \t Age: %i \n", people[i].name, people[i].age);
}
return 0;
}
【问题讨论】:
-
请勿发布代码图片,请发布代码本身。
-
试试
struct person *people;->struct person *people[HOW_MANY]; -
@Annabelle:不,这是 C 而不是 C++。
-
@Marian: ... 并将
insert(&people, ...更改为insert(people, ...。 -
@Annabelle:您链接的问题只是带有错误的标签,即 C 标签,该标签也是后来才添加的,显然没有仔细阅读问题。在 C 中,
struct类型 always 需要携带struct。这在 C++ 中是不同的。