Pulling values out of one multidimensional array and putting them into several 1D arrays (C)

Pulling values out of one multidimensional array and putting them into several 1D arrays (C)

I am trying to sort the values in the Data array into Column arrays X1,X2, and Y_actual. The code I have written out makes sense to me, and returns the correct array1,array2, and array3 values if I print them within the Data_Sort function, but the X1, X2, and Y_actual arrays are incorrect. For reference X1 = {0,1,2,3} which is correct but X2 = {1,2,3,6} and Y_actual = {2,3,6,12}. I want it to sort like this X1 = {0,1,2,3} and X2 = {0,2,4,6} etc

int Data[4][3] = {{0,0,0},{1,2,4},{2,4,8},{3,6,12}};
int X1[] = {};int X2[] = {};int Y_actual[] = {};
int Data_Sort (int *array1, int *array2, int *array3){
    for(int i = 0; i<4; i++){
        array1[i] = Data[i][0];
        array2[i] = Data[i][1];
        array3[i] = Data[i][2];}
int main()
{
Data_Sort(X1, X2, Y_actual);
return 0;
}

Answer

You need to allocate space for the arrays with a fixed size, like this:

int Data[4][3] = {{0,0,0},{1,2,4},{2,4,8},{3,6,12}};  

int Data_Sort (int *array1, int *array2, int *array3){
    for(int i = 0; i<4; i++){
       array1[i] = Data[i][0];
       array2[i] = Data[i][1];
       array3[i] = Data[i][2];
    }
    return 0; 
}

int main() {
    int X1[4], X2[4], Y_actual[4];
    Data_Sort(X1, X2, Y_actual);
    // Optional: Print to verify
    for (int i = 0; i < 4; i++) {
        printf("X1[%d] = %d, X2[%d] = %d, Y_actual[%d] = %d\n", i, X1[i], i, X2[i], i, Y_actual[i]);    
    }
    return 0; 
}

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles