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|2|3|4|5|6|
-------------
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:
malloc()
instead of 1 + N
arr[i][j]
And is it feasible at all?
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.