I would like to know if, given the declarations below:

int first[1][COLUMN_NUMBER];
int second[COLUMN_NUMBER];

the two bi-dimensional arrays could be accessed in the same or in a similar way. What I mean is: are they exchangeable? I am asking this because, due to an upgrade, I would like to avoid the refactoring of all the code I have written before.

Thanks a lot.

有帮助吗?

解决方案 2

A 2D array and a 1D array of same size are not same/similar although a 2D array can be represented as a 1D array (strictly speaking the behavior is undefined).

What I mean is: are they exchangeable?

It may depends on the situation.
A simple difference you can see by calling a function

void foo(int *p)  
{

}

for the two cases. The first can be passed to foo either by passing &first[i][j], *first or first[i] (where i and j are int type and representing the row and column index within array bound) while array second can be passed as second or &second[i].
You can not pass first (unlike second) and second[i] (unlike first[i]) to the foo as an argument because they are incompatible with the expected parameter of foo (which is of int *).

其他提示

According to this piece of code, there should be no difference.

#include <stdio.h>

int main(void) {
    int const COLUMN_NUMBER = 10;
    union {
      int first[1][COLUMN_NUMBER];
      int second[COLUMN_NUMBER];
      } u;
    u.first[0][5] = 3;
    printf("%d\n", u.second[5]);
    return 0;
}
int first[1][10];
int second[10];

For this example the two statements makes no difference in memory allocation. The first statement declares an array with 1 row and 10 columns. Similarly the second statement makes an array which has simply 10 elements. Logically two statements differ but here both are occupying same memory space. In case of first statement, if we have int first[10][10] then it will declare an array of 10 rows and 10 columns.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top