I'm trying to understand why this doesn't work as I want it to. I'm trying to malloc an integer pointer inside a function and return to the main function with the values intact. I assumed you can do this as the integer pointer is just an address, same with the size variable. So I thought the newPtr will have the contents of the values but it does not. Why is this?
I tried to see how to make this work but only idea I've come up with is to make function parameter type int * * arr.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
bool readData(int * arr, int * size);
int main() {
int i;
int countSize = 10;
int * newPtr;
bool rtv = true;
rtv = readData(newPtr, &countSize);
if (rtv == false) {
printf("read data failed\n");
return -1;
}
for (i = 0; i < countSize/2; i++) {
printf("%d\t", newPtr[i]);
}
printf("\n");
printf("new size: %d\n", countSize);
free(newPtr);
return 0;
}
bool readData(int * arr, int * size) {
int i;
arr = malloc(sizeof(int*) * *size);
if (arr == NULL) {
printf("malloc error\n");
return false;
}
for (i = 0; i < *size; i++) {
arr[i] = i * i;
}
for (i = 0; i < *size; i++) {
printf("[%d] = %d\n", i, (arr)[i]);
}
*size = *size * 2;
return true;
}