向前声明一个指向结构的指针数组搞砸了吗?

时间:2013-10-05 03:24:11

标签: c arrays pointers struct forward-declaration

我有一个名为S的结构和一个名为A的结构S指针数组。我的函数T将一个指向struct S的指针作为参数。

struct S *A; //forward declare array A of (pointers to) structs

...
void T(struct S *s){//function that accepts pointer to struct S
     ...
}

void otherFunction(){
     ...
     T(A[i-1]); //Yields error Incompatible type for argument 1
}

int main(){
     A = malloc(100 * sizeof(struct S*)); //initialize array
     int i;
     for(i = 0; i < NumBowls; i++){
         A[i] = malloc(100 * sizeof(struct S));//initialize structs in array
     }
     otherFunction();
}

使用print语句,我能够看到A [i-1]是struct S类型,但不是指向S的指针,这是我想要的。可能这是因为我转发声明的A?

2 个答案:

答案 0 :(得分:1)

struct S *A; // this is a pointer of struct S  type.

您需要声明

 struct S **A; // pointer to pointer

 struct S *A[MAX_SIZE]; //array of pointers 

答案 1 :(得分:0)

struct S *A;

声明你需要的指针数组

struct S *A[10];


A[i] = malloc(sizeof(S));