I have a problem returning dynamic array pointer with function parameter. I get segfault
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n)
{
ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
*(ptr + (i - 1)) = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(array, n);
for(int i = 0; i < n; ++i)
{
printf("%d", array[i]);
}
return 0;
}
I have to fill my array with i*i, when I is from 1 to n. I don't get any errors or warnings. Just message about segmentation fault. Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
*(ptr + (i - 1))instead of the easier to readptr[i - 1]?*ptr[i - 1], because it's the same as*(ptr[i - 1])while you need(*ptr)[i - 1].int *createArray(int n)function and make it return a pointer to the allocated memory. Call it asarray = createArray(n);.