gpt4 book ai didi

c - 声明结构类型,将值插入到该类型的数组中,并打印出数组

转载 作者:行者123 更新时间:2023-12-02 05:26:38 25 4
gpt4 key购买 nike

在这个程序中,我想定义一个名为 person 的结构,以及一个插入函数,用于将一个元素插入到声明为类型 person 的数组中未使用的空间中。最后,我想将结果作为标准输出打印出来。谁能给我一个提示来纠正任何错误的地方?干杯

错误:

arrays.c:16:22: error: expected ')' before '[' token
arrays.c: In function 'main':
arrays.c:34:5: warning: implicit declaration of function 'insert'
arrays.c:41:5: warning: format '%s' expects type 'char *', but argument 2 has type 'char **'

代码

#include <stdio.h>

/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array */
char *names[7]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[7]= {22, 24, 106, 6, 18, 32, 24};


/* declare your struct for a person here */
typedef struct{
char name;
int ages;
} person;

static void insert (p[], char *name, int ages) {

static int nextfreeplace = 0;
/* put name and age into the next free place in the array parameter here */
person p[0] = {&name, age};

/* modify nextfreeplace here */
nextfreeplace++;

}

int main(int argc, char **argv) {

/* declare the people array here */
person p[7];

//insert the members and age into the unusage array.
for (int i=0; i < 7; i++) {
insert (p[i], &names[i], ages[i]);
p[i]= p[i+1];

}

/* print the people array here*/
for (int i=0; i < 7; i++) {
printf("%s is %d years old\n", &names[i], ages[i]);
}

return 0;
}

最佳答案

第一个问题是你的struct person。您将名称声明为 char,而它应该是 char*(指针)char[](数组)。。

typedef struct 
{
char *name; //or char name[100];
int age;
}
person;

接下来,您的insert function 参数不正确。您不需要一组人员(您可以这样做,但这更简单),您需要一个指向人员结构的指针,以便您可以对其进行编辑。

static void insert(person *p, char *name, int age)
{
p->name = name;
p->age = age;
}

最后,这是填充数组并将其打印出来的方式:

int main()
{
//names and ages...

person people[7];

for (int i = 0; i < 7; i++)
{
insert(&people[i], names[i], ages[i]);
}

for (int i = 0; i < 7; i++)
{
printf("name: %s, age: %i\n", people[i].name, people[i].age);
}
}

示例:http://ideone.com/dzGWId .

关于c - 声明结构类型,将值插入到该类型的数组中,并打印出数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com