我正在尝试初始化在 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;
}
有人可以解释一下为什么某些功能有效而其他功能无效吗?