0

While writing C-code for an answer to a question about a limited-memory situation, I wondered whether any memory space can be saved by using a flat array instead of a (rectangular) two-dimensional array (of which the size is known at compile-time).

So, does e.g. char a[200][100] use more memory space than char a[20000]?

(I know it does in some languages, but this is specifically about C)

  • 2
    It would occupie same amount of memory as 1-D array only difference would be how they are accessed . – ameyCU Jul 29 '16 at 04:12

2 Answers2

3

So, does e.g. char a[200][100] use more memory space than char a[20000]?

No, char a[200][100] uses the same amount of memory as char a[20000].

Both need contiguous memory that can hold 20000 chars.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

There is no difference between a[200][100] and a[20000]. For the a[200][100] C uses the number of columns to compute the offset as a is just a pointer to memory of type char. So if you wanted a[20][5] then C would compute a[20][5] = *(a + 20 * 100 + 5); I should mention that C is row major (or uses row first in computations).

So if you know the dimensions of your array, you could do the same computation with a[20000].

From a software communications standpoint, if it was static, I would use the char a[200][100] as it communications your structure is 200 rows by 100 columns. This lets the compiler do the computations for you.

Glenn
  • 1,169
  • 1
  • 14
  • 23