2012-10-21 53 views
2

在此程序中,我试图创建一个结构体,然后使用该结构体类型初始化一个数组,将名称和年龄放入数组中,并打印出结果。然而,当我编译文件,它说,“姓名”和年龄”是不是结构或联合。任何人都可以发现我的错误,请,谢谢编译错误:请求不是结构或联合错误

#include <stdio.h> 
#include <stdlib.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 *names; 
    int ages; 
} person; 

static void insert (person **p, char *s, int n) { 

    *p = malloc(sizeof(person)); 

    static int nextfreeplace = 0; 

    /* put name and age into the next free place in the array parameter here */ 
    (*p)->names=s; 
    (*p)->ages=n; 

    /* 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("name: %s, age:%i\n", p[i].names, p[i].ages); 
    } 

} 

回答

2

声明p为指针数组结构。在printf的行,取消引用一次pp[i],但p是仍然是一个指向结构的指针,你想与->

for (int i=0; i < 7; i++) { 
    printf("name: %s, age:%i\n", p[i]->names, p[i]->ages); 
} 

访问及其字段,并为你增加i你的循环,你不需要移动你的p [i]指针,删除,p[i] = p[i + 1]

for (int i=0; i < 7; i++) { 
    insert (&p[i], names[i], ages[i]); 
} 
1

person *p[7]声明七个指针数组person,所以p[i]是一个指向结构。因此,您需要取消引用此指针以访问其成员。

printf("name: %s, age:%i\n", (*p[i]).names, (*p[i]).ages); 

为了提高可读性,您可以使用后缀运算符->

printf("name: %s, age:%i\n", p[i]->names, p[i]->ages); 

C11 (1570), § 6.5.2.3 Structure and union members
A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points, and is an lvalue) If the first expression is a pointer to a qualified type, the result has the so-qualified version of the type of the designated member.

相关问题