1

I'm trying to do a simple 2D array for student grades but it keeps giving me a error for "variable not initialized".

#include <stdio.h>

int main()
{
    int const rows = 3;
    int const columns = 4;

    int studentsGrades[rows][columns] = {
        {1, 3, 4, 6},
        {3, 2, 4, 5},
        {32, 2, 4, 9}
        };

    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

2 Answers2

0

You need to switch from int rows = 3; to const int rows = 3;.

That is because an array's size does not change; it has a constant size in memory.

XDarkDev
  • 46
  • 1
  • 8
  • Yes, i forgot that, but the error presist in the variable... i've tried but didnt work, thanks anyway – ricardomart Nov 21 '20 at 15:34
  • Could you please reflect more on what you're doing? I have tried this and it works perfectly fine. – XDarkDev Nov 21 '20 at 15:38
  • Try and add the following piece of code below the `studentsGrades` variable: `printf("%d\n", studentsGrades[2][2]);`, compile and run the code anyways, and see if the program runs and prints `4` to the terminal. If so (and it must), then the problem is your Text Editor/IDE, not your C code. – XDarkDev Nov 21 '20 at 15:41
  • The use of a `const` variable as an array index, in order to make it *not* a VLA is, technically, a C++ feature. It is an *extension* in C99, I think. Clang-cl gives this: **warning : variable length array folded to constant array as an extension [-Wgnu-folding-constant]** – Adrian Mole Nov 21 '20 at 16:09
  • I´ve tried to print out the studentsGrade anyway and it doesnt work, i switched do c++ and it worked... Do you know a way of doing this in c? and by the way i'm kinda of a noob, can you tell me what is VLA? – ricardomart Nov 21 '20 at 16:43
  • @AdrianMole Would you care explaining what VLA is? I have not really heard of it before. – XDarkDev Nov 21 '20 at 17:07
  • VLA: Variable Length Array. – Adrian Mole Nov 21 '20 at 17:11
  • @AdrianMole So C11 supports VLA? How? Because I'm compiling with `-std=c11` and it's compiling fine. – XDarkDev Nov 21 '20 at 17:28
0

In C, you are not allowed to use initializers with VLA's(You can check the C99 standard). You can either use memset, or #define your array size instead.

This works:

#include <stdio.h>

#define rows 3
#define columns 4

int main(void)
{
    int studentsGrades[rows][columns] = {
        {1, 3, 4, 6},
        {3, 2, 4, 5},
        {32, 2, 4, 9}
        };

    return 0;
}

You might also want to check out this post.

alex01011
  • 1,670
  • 2
  • 5
  • 17