【发布时间】:2021-08-01 21:49:45
【问题描述】:
一段时间以来,我一直在寻找解决方案。我想我知道发生了什么以及解决方案应该是什么,但是我不太确定如何实施。
我有一个包含两个可变长度数组的结构。这些将在函数中填充并返回给调用函数以进行处理。 问题似乎是当被调用函数超出范围时,可变长度数组的任何分配都变得无效。我猜想一个解决方案可能是在堆上分配内存,然后在我完成调用函数中的结构后释放内存。下面给出一个代码示例
struct fields {
int n;
double * A;
double * B;
};
struct fields field() {
int n = 4;
double A[n] = { 1, 2, 3, 4 };
double B[n] = { 1, 2, 3, 4 };
struct fields field;
field.n = n;
field.A = A;
field.B = B;
/* field can be accessed with n, A, B set properly */
return field;
}
double calling_function() {
struct fields field1 = field();
/* field1 contains n but A and B have not returned */
.
.
.
}
【问题讨论】:
-
I would guess that a solution may be to allocate the memory on the heap and then free the memory once I am done with the struct in the calling function.-- 这可能是个不错的猜测。 -
吹毛求疵,但你没有可变长度数组的结构(这实际上是不可能的),但是你有一个带有 pointers 的结构并且这些指针必须指向生命周期将比结构本身(或结构的任何副本)更长的东西。
-
您所做的基本上是返回指向局部变量的指针,这是从未被允许的。局部(非静态)变量在其作用域结束之前都有一个生命周期。对于数组
A和B,这是函数返回的时间。参见例如How to access a local variable from a different function using pointers? 关于这个主题的一个较早的问题。
标签: arrays c struct scope heap-memory