Search code examples
arrayscdynamically-sized-type

How to allocate dynamically-sized 2d array using only one malloc with double-square-brackets (arr[i][j]) access syntax in C?


Have C classes in university, but now hours of googling haven't answered my question.

I know that there are compiled-time arrays in C like:

#define N 2
#define M 3

int array[N][M] = { { 1, 2, 3 }, 
                    { 4, 5, 6 } };

This array:

  1. Allocated in memory uniformly: like
-------------
|1|2|3|4|5|6|
-------------
  1. I can access it by simple:
arr[i][j]

But if I want to have similar array but dynamically sized?

I've seen this answer, which suggests:

int main() {
  int N, M;
  scanf("%d %d", &N, &M);

  int (*arr)[N] = malloc(sizeof(int[N][M]));

  return 0;
}

This looks like what I search for, but my Visual Studio refuses to compile it:

1>C:\Users\Name\VisualStudioProjects\lab2\lab2\lab51.c(18,26): error C2057: expected constant expression
1>C:\Users\Name\VisualStudioProjects\lab2\lab2\lab51.c(18,27): error C2466: cannot allocate an array of constant size 0

I've tried to set Project -> Properties -> General -> C Language Standard to "ISO C11 Standard", but this didn't help.

Could you hint me the proper way to achieve what I want in C? Namely:

  1. 2d array
  2. Dynamically allocated using non-constant sizes
  3. Using only one malloc() instead of 1 + N
  4. Having access syntax as arr[i][j]

And is it feasible at all?


Solution

  • Could you hint me the proper way to achieve what I want in C? Namely:

     1. 2d array
     2. Dynamically allocated using non-constant sizes
     3. Using only one malloc() instead of 1 + N
     4. Having access syntax as arr[i][j]
    

    Unfortunatelly you are out of luck as you use MS compiler which does not support VLAs. You need workarounds.

    1. Only as an array of pointers or single dimension array and macros or functions to access the elements
    2. Same as p. 1
    3. Only as 1D array
    4. Only as an array of pointers.