我正在尝试初始化在 C 结构中声明的数组。
目标是使用一个数组并将其作为参数传递给一个函数,然后该函数复制传递的数组的每个元素并将其分配给结构内的数组。
#include <stdio.h>
typedef struct {
int v;
int arrayInStruct[];
} TEST;
void ProblemCode1(){
TEST test1; //Array Declared after struct declaration.
int array[5] = {1,2,3,4,5};
for(int i = 0; i < 5; i++){
test1.arrayInStruct[i] = array[i];
printf("%d", test1.arrayInStruct[i]);
}
return;
}
void ProblemCode2(int a[]){
//Array Pass by Value and elements assigned to struct array.
TEST test2;
test2.arrayInStruct[5] = 0;
for(int i = 0; i < 5; i++){
test2.arrayInStruct[i] = a[i];
printf("%d", test2.arrayInStruct[i]);
}
return;
}
void ProblemCode3(int a[]){
//Array Pass by Value and elements assigned to struct array
//and struct array initilzation missing as compared to ProblemCode2.
TEST test2;
for(int i = 0; i < 5; i++){
test2.arrayInStruct[i] = a[i];
printf("%d", test2.arrayInStruct[i]);
}
return;
}
void WorkingCode1(){
int array[5] = {1,2,3,4,5};
TEST test1; //Array Created Before Declaration of Struct and not passed via function.
for(int i = 0; i < 5; i++){
test1.arrayInStruct[i] = array[i];
printf("%d", test1.arrayInStruct[i]);
}
printf("\n");
return;
}
void WorkingCode2(){
int array1[5] = {1,2,3,4,5};
int array2[5] = {0};
for(int i = 0; i < 5; i++){
array2[i] = array1[i];
printf("%d", array2[i]);
}
printf("\n");
return;
}
int main(){
//int passbyValue[] = {1,2,3,4,5};
//ProblemCode1();
//ProblemCode2(passbyValue);
//ProblemCode3(passbyValue);
WorkingCode1();
WorkingCode2();
return 0;
}
有人可以解释一下为什么某些功能有效而其他功能无效吗?
您的结构体类型包含一个灵活数组成员,即最后一个成员是未指定长度的数组。此类结构体的大小不包括灵活数组成员的大小。
仅当结构体的实例被动态分配时,才能真正使用这些成员,即为结构体本身分配足够的空间,并为一定数量的数组元素分配足够的空间。
由于您在堆栈上声明了此结构体的实例,因此没有空间容纳灵活数组成员。这意味着,每当您尝试读取或写入数组元素时,您都会访问声明结构体边界之外的内存。这样做会在代码中触发未定义的行为。
由于您始终将此数组视为具有 5 个成员,因此最简单的解决方法是将结构中的数组明确声明为该大小:
或者,如果您想保留灵活数组成员,则需要动态分配所使用的结构的任何实例,为灵活数组成员添加足够的空间: