Assign pointer to the array inside a function

3

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.

    
asked by anonymous 11.02.2018 / 07:10

1 answer

5

The problem is that when doing new assignment inside the function, you are not taking advantage of the original pointer, but creating a new one (which is discarded in return).

In these cases, I believe that making a copy is a reasonable solution:

void retorna_algo(int size, int* destino){
  if (size == 1){
    *destino = 1;
  } else if (size == 3) {
    memcpy(destino, (int[]){1, 2, 3}, 3*sizeof(int));
  }
}

See working at IDEONE .

    
11.02.2018 / 15:40