When you dynamically assign a C language array...

Asked 2 years ago, Updated 2 years ago, 127 views

#include <stdio.h>

int main()
{
    int * arr1 = (int *)malloc(sizeof(int) * 6);
    int * arr2 = (int *)malloc(sizeof(int) * 6);
    int * arr3 = (int *)malloc(sizeof(int) * 6);

    arr1[3][2] = {
        {3, 4},
        {5, 2},
        {1, 2},
    };

    arr2[3][2] = {
        {1, 2},
        {7, 9},
        {3, 5}
    };

    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 2; j++)
            arr3[i][j] = arr1[i][j] * arr2[i][j];


    for (int i = 0; i < 3; i++)
        printf("%d %d\n", arr3[i][0], arr3[i][1]);

    free(arr1);
    free(arr2);
    free(arr3);
    return 0;
}

Is it right to assign and declare such a dynamic arrangement? In every line that has an array, subscripted value is neither array nor pointer nor vector There's an error like this...

c dynamic-allocation array pointer

2022-09-20 10:28

1 Answers

It's a mix of different methods.

arr3[i][j]

If you want to use it like this, you must have a pointer to arr3[0], a pointer to arr3[0][0], and a pointer to arr3[1][0]

int * arr1 = (int *)malloc(sizeof(int) * 6)

If you want to use it like this, you have to use it like arr1[0] = 3; arr1[1] = 4; etc.

Additionally, because the program does not know what array size the user is using, it is not possible to initialize the array, such as {{3, 4}, {...}}.

Additionally, in the arr1[3][2] part, there is a comma since the last {1, 2}.


2022-09-20 10:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.