Search code examples
cpointersdynamic-arrays

Split array into dynamic array and return ptr


I have a problem. I have to divide array into dynamic array and return pointer with parameter.

When I try to run this code, I get (interrupted by signal 11: SIGSEGV) this message. I think it is something with my pointers. But I don't even get any warnings, I don't know where to look else.

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

int splitData(int data[], int size, int splitPlace, int **firstArray);

int main() {

    int data[6] = {1, 2, 3, 4, 5, 6};
    int size = 6;
    int *ptr = NULL;
    int n = splitData(data, size, 3, &ptr);
    printf("%d", n);

    for(int i = 0; i < 3; ++i)
    {
        printf("[%d]", ptr[i]);
    }
    return 0;
}

int splitData(int data[], int size, int splitPlace, int **firstArray)
{

    *firstArray = (int *)malloc(splitPlace * sizeof(int));

    for(int i = 0; i < splitPlace; ++i)
    {
        *firstArray[i] = data[i];
    }
    return 0;
}

Solution

  • You have the precedence wrong with *firstArray[i]. You need (*firstArray)[i].

    Clearer might be to allocate

    int *new_array = malloc(...);
    *firstArray = new_array.
    

    Then use new_array in your loop body.