I'm trying to write a function that assigns an integer or list of integers to a pointer, depending on a parameter. But the assignment does not work inside it, just outside:
void retorna_algo(int size, int* destino){
if (size == 1){
*destino = 1;
} else if (size == 3) {
destino = (int[]){1, 2, 3};
}
}
int main(void) {
int *ponteiro;
ponteiro = malloc(sizeof(int));
retorna_algo(1, ponteiro);
printf("%d\n", *ponteiro); // Escreve "1" - como esperado
ponteiro = realloc(ponteiro, sizeof(int)*3);
retorna_algo(3, ponteiro);
printf("%d | %d | %d\n", ponteiro[0], ponteiro[1], ponteiro[2]);
// Escreve "1 | 0 | 0", basicamente mantendo o valor zerado do malloc e realloc
return 0;
}
Using destino = (int[]){1, 2, 3};
outside the function actually assigns the array to the pointer, but within it nothing ... As if the scope were affecting the assignment. I think it makes some sense, since it is an assignment of the array pointer to the address of the declared literal. And the literal address is discarded when the function is terminated.
It seems to me that the problem is in the way the assignment is done (with cast to (int[])
), but I could not find any other cast that worked.