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:
- Allocated in memory uniformly: like
-------------
|1|2|3|4|5|6|
-------------
- 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:
- 2d array
- Dynamically allocated using non-constant sizes
- Using only one
malloc()instead of1 + N - Having access syntax as
arr[i][j]
And is it feasible at all?
Unfortunatelly you are out of luck as you use MS compiler which does not support VLAs. You need workarounds.