2012-10-20 32 views
2

在此程序中,我想定义一个名为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; 
} 
+0

'nextfreeplace'变量的位置是可疑的。您需要知道数组中有多少行(这是变量记录的内容),用于循环数据等,并删除它们。除了当前的问题,您可能需要使其更加明显。此外,你将无法清空数组;你也不能有两个单独的由该函数管理的人员阵列。 –

回答

2

你必须与参数p一个问题。

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

你忘记它的类型(person)。然后你重新声明它;以下指令无效:

person p[0] = {&name, age}; 

在函数调用中,您不使用数组,而是使用数组的情况。所以,你的功能应该是:

typedef struct 
{ 
    char *name; 
    int ages; 
} person; 

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

和呼叫:

insert (&p[i], names[i], ages[i]); 
3

第一个问题是你的结构的人。您声明的名称为char,而它应该是char *(指针)char [](array)

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

接下来,您插入功能有不正确的参数。你不想要一组人(你可以做到这一点,但这很简单),你想要一个指针指向一个人struct,所以你可以编辑它。

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