-3

所以几天前我刚刚开始用 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;
}
4

4 回答 4

2

声明后需要一个分号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++)
于 2013-10-24T14:49:54.200 回答
2

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

将解决您问题中的主要问题

于 2013-10-24T14:58:44.343 回答
1
  • 第 19 行,预期为 ';' 结构后
  • 第 46 行:预期的 ';' 在“for”语句说明符中,应为“;” 在表达式之后,for 循环的主体为空
  • 第 26 行将“struct person”传递给不兼容类型“const void *”的参数

基本上,添加一个 ; 在结构的右大括号之后。您的 for 循环中有一个杂散的 ) 。后者更复杂。

于 2013-10-24T14:49:32.817 回答
0

像这样

char *names[]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
          "Harriet"};
int ages[]= {22, 24, 106, 6, 18, 32, 24};

一个想法是这样做:

char *names[]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
          "Harriet", 0}; //notice the 0
for(int i=0;names[i];i++)
{
  printf("%s",names[i]);
}

但我不确定这是最好的实现。

于 2013-10-24T14:44:54.930 回答