0

I'm back again with that C question heh. So I'm trying to get the user to input a whole 2d array (size, values, everything), with VLA arrays (im using the latest compiler). Everything is fine up until I get the nested for loop, then it saves the last value into the array and ignored anything before it. I cannot seem to figure out how to fix my VLA to iterate through every element in the array and assign the value typed in by the user, all I get is it saving my last value into the whole array. Through some testing I've found that my problem is contained in my Inner loop of my nested for loop. EDIT: Through the help of Weather Vane, it was figured out that the array needs to be initialized after my x and y are saved, but now it saves my last value in the whole array and not every value typed. Here's my code snippet:

   int x, y, row, col, a = 0;
   //int NxM[x][y]; Moved 
   bool counter[10]; //I have 1 last part to code that involves this

   printf("This program counts occurrences of digits 0 through 9 in an NxM 
   array.\n");

   printf("Enter the size of the array (Row Column): ");
   scanf("%d %d", &x, &y);
   int NxM[x][y]; //Moved here.
   for(row = 0; row < x; row++){
       printf("Enter row %d: \n", a);
       a++;
      for(col = 0; col < y; col++){


               scanf("%d ", &NxM[x][y]);//Why you only save 1 value >.<
        }


   }

(The reason I have my printf statement between my loops was to test where my looping problem was, and because I need my printf to look like Enter row 0 Enter row 1 etc..)

11
  • 3
    int NxM[x][y]; is using undefined values. Move it down below scanf("%d %d", &x, &y); and check the return value from scanf as well as the values too. Suppose Noddy enters -1 -2 ? Commented Mar 15, 2018 at 19:55
  • x and y are initialized above, should I set them equal to 0? Commented Mar 15, 2018 at 19:56
  • 3
    Nope, they are not initialised before int NxM[x][y]; . C is not a forward-thinking language. It does not wait until later and track what you are doing. It uses the values it knows for x and y at the time you use them. Commented Mar 15, 2018 at 19:57
  • 1
    So. You just fixed my problem............................... I feel so dumb. OH so because x and y were basically just floating variables when the array was put in, they werent used in the evaluating of the dimensions of the array in my for loop, or am i off base completely? Commented Mar 15, 2018 at 19:59
  • Alright that fixed my for loop, unfortunately, now when it iterated through my loop it saves the final input in the whole array. (say the user last inputs 4, the whole array is 4) Commented Mar 15, 2018 at 20:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.