Home > Software design >  How to return dynamic array with function parameters
How to return dynamic array with function parameters

Time:11-17

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)

CodePudding user response:

Memory must be allocate in the calling function, but not in called. This variant works:

#include <stdio.h>
#include <stdlib.h>

void createArray(int *ptr, int n){
 int i;
    for(i = 1; i <= n; i  )    {
        *(ptr   (i - 1)) = i*i;
// fprintf(stdout,"%d %d\n", i, *(ptr   (i -1)));fflush(stdout);
    }
}

int main() {
    int i, n, *array = NULL;
 void *pvc;
    n = 5;
    array = (int *)malloc(n * sizeof(int));
    createArray(array, n);
    for(i = 0; i < n; i  )    {
        fprintf(stdout,"%d %d\n", i, array[i]);fflush(stdout);
    }
 pvc = (void *)array;
 free(pvc);
    return 0;
}

CodePudding user response:

You can change pointer through function parameters like this:

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);

Remember to call function like this: createArray(array, n);

  • Related