gpt4 book ai didi

C STRUCT strcopy EASY BEGINNER PROGRAM - 无法修复编译错误

转载 作者:行者123 更新时间:2023-11-30 20:47:29 32 4
gpt4 key购买 nike

几天前我刚刚开始用 C 语言编程,现在我正在尝试学习结构。

我有这个程序,但不幸的是由于某种原因我没有编译。我花了很多时间试图修复它,但我似乎找不到任何问题。

以下是我遇到的编译错误:

arrays.c:21: error: two or more data types in declaration specifiers
arrays.c: In function ‘insert’:
arrays.c:26: error: incompatible type for argument 1 of ‘strcpy’
/usr/include/string.h:128: note: expected ‘char * restrict’ but argument is of type ‘struct person’
arrays.c:32: warning: no return statement in function returning non-void
arrays.c: In function ‘main’:
arrays.c:46: error: expected ‘;’ before ‘)’ token
arrays.c:46: error: expected ‘;’ before ‘)’ token
arrays.c:46: error: expected statement before ‘)’ token

我不确定我的代码出了什么问题,我什至在我的 main 函数中遇到了错误(第 46 行)

这是我的完整程序代码:

#include <stdio.h>
#include<string.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 [32];
int age;
}

static void insert (struct person people[], char *name, int age)
{
static int nextfreeplace = 0;
static int nextinsert = 0;
/* put name and age into the next free place in the array parameter here */
strcpy(people[nextfreeplace],name);
people[nextfreeplace].age = age;

/* modify nextfreeplace here */
nextfreeplace = nextfreeplace + 1;
nextinsert = nextinsert + 1;
}

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

/* declare the people array here */
struct person people[12];

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

/* print the people array here*/
for (i =0; i < HOW_MANY); i++)
{
printf("%s\n", people[i].name);
printf("%d\n", people[i].age);
}
return 0;
}

最佳答案

您在 struct 声明后需要一个分号:

struct person
{
char name [32];
int age;
}; /* <-- here */

您还需要更正 strcpy() 调用以使用 name 字段:

strcpy(people[nextfreeplace].name, name);

并且您在 for 循环中有一个杂散的 ):

for (i =0; i < HOW_MANY); i++)

...应该是:

for (i =0; i < HOW_MANY; i++)

关于C STRUCT strcopy EASY BEGINNER PROGRAM - 无法修复编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569102/

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