Search code examples
cc89

How to get a cell value from an array dynamically? [C89]


I have this array :

array[0][0] = 1; 
array[0][1] = 2;
array[0][2] = 3;
array[0][3] = 4;

How could I do something like this ?

int a = 0;
int b = 1;

printf("%d",array[a][b]);

C89 is a requirement. Here is a MCVE:

int main(int argc, char *argv[])
{
    int array[0][4] = {1, 2, 3, 4}, i = 0;

    for (i = 0 ; i < 4 ; i++)
    {
        printf("%d\n", array[0][i]);
    }

    return 0;
}

Output:

1512079328
32764
0
3

Solution

  • Your array needs at least 1 in the first dimension and 4 in the 2nd.

    int array[1][4];
    //        ^  ^
    

    Reason: Arrays in C and C++ have valid indexes from 0 up to size - 1. So if you want to access indexes 0 ... 3 the size of the array has to be at least 4.