【发布时间】:2022-01-09 20:04:19
【问题描述】:
各位, 我有一个问题和一个问题。 希望你能帮我解释一下。
首先我有两个结构:
typedef struct {
double x;
double y;
} A;
typedef struct {
unsigned int count;
A(*stack)[];
}B;
我在 main() 中声明了这个结构 B,并将 B 的指针传递给将初始化的函数
main(){
B x;
function rr(&x);
}
void rr(B* test) {
test->stack= malloc((4) * sizeof(A)); //4Elements
for (unsigned int i = 0; i < 4; i++) {
(test->stack+ i)->x= 89;
}
}
在这条线上 (测试->堆栈+ i)->x= 89; 编译器说不完整的类型 我知道为什么它在结构 B 中不完整,因为它们没有维度。 但是数组应该在函数 rr 中初始化
也许你明白我的意思以及如何解决我的问题。 函数 rr 我不允许更改。
问候
编辑 1 谢谢大家的回答 或许我应该解决我的问题
typedef struct {
unsigned int count;
A(*stack)[]; // here i want a pointer to an array of A's
}B;
//over main it is declared
void rr(B*);
main(){
B x;
function rr(&x);
}
// this func is not allowed to change
void rr(B* test) {
test->stack= malloc((4) * sizeof(A)); //4Elements
for (unsigned int i = 0; i < 4; i++) {
(test->stack+ i)->x= 89; // error cause incomplete type but i
//have to use this line
}
}
希望现在我更容易理解我想要什么
【问题讨论】:
-
function rr(&x);不是正确的 C 代码,至少在没有function的一些定义的情况下不是。您也可能在声明之前尝试使用rr。您应该编辑问题以提供minimal reproducible example。 -
“function rr i am not allowed to change”这句话不清楚。你的意思是你根本不允许更改
rr的任何源代码?或者只是不允许您更改其参数类型?还是别的什么? -
test->stack+ i失败,因为在声明stack时,编译器不知道它指向的东西有多大。test->stack+ i表示要计算一个指针,该指针指向i元素之外的test->stack点,其中元素类型是一个未知大小的数组。由于大小未知,因此无法进行计算。为了帮助人们回答,您应该说明您想使用test->stack做什么。如果只是指向A对象数组的第一个元素,请将其声明更改为A *stack;。 -
您还没有提供minimal reproducible example。要干净地编译,直到您询问错误为止,您的代码需要
#insert <stdlib.h>和function的定义。我们可以轻松插入前者,但您应该提供后者或将其从问题的代码中删除。您还应该将main()更改为int main(void);。 -
第二,正如您所知道的,将
A(*stack)[];更改为A *stack;可能就足够了。如果不是,您应该解释原因。你说你想要一个“指向 A 的数组的指针”,但是以普通方式使用“指向数组”的指针的标准 C 方法是使用指向第一个元素的指针,它的类型为A *。这用作指向数组的指针,因为它可用于访问数组,如test->stack[i]、test->stack[i].x和(test->stack + i)->x。从技术上讲,它的类型不是“指向数组的指针”,但通俗地说,因为它符合我们的目的。
标签: c struct typedef incomplete-type