Estou tentando inicializar um array que é declarado em C struct.
O objetivo é usar um array e passá-lo como um argumento para uma função, que então copia cada elemento do array passado e o atribui a um array dentro de uma struct.
#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;
}
Alguém poderia explicar por que certas funções funcionam e outras não?