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

时间:2013-10-24 14:43:33

标签: c string struct compilation compiler-errors

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

我不确定我的代码有什么问题,我的主要功能甚至出错(第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 个答案:

答案 0 :(得分: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++)

答案 1 :(得分:2)

的strcpy(人[nextfreeplace] .name和名称);

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

答案 2 :(得分:1)

  • 19号线,预计';'在struct
  • 之后
  • 第46行:预期';'在'for'语句说明符中,期望';'表达式之后,for循环有空体
  • 第26行将'struct person'传递给不兼容类型'const void *'
  • 的参数

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

答案 3 :(得分: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]);
}

但我不确定这是最好的实施方式。