-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

コードの何が問題なのかわかりません。メイン関数でもエラーが発生しています (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

strcpy(人[次のフリープレイス].name,name);

質問の主要な問題を解決します

于 2013-10-24T14:58:44.343 に答える
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 に答える
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 に答える