I have more of a question than a problem. I am doing the CS50 introduction to computer science course and came across something that I don't understand and wondered if I could get an opinion.
I am printing a 2D array, here was my code and the first outcome.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
int a[2][3], i, j;
//collecting values for matrix
//rows
for (i = 0; i < 2; i )
{
//columns
for (j = 0; j < 3; j )
{
***get_int("Pls provide values for matrix: ");***
}
}
//printing the matrix
for (i = 0; i < 2; i )
{
for (j = 0; j < 3; j )
{
printf("%i\t", a[i][j]);
}
printf("\n");
}
}
I entered the following in my terminal as response: 1 2 3 4 5 6
this leads to this response:
0 0 4198480
0 -1885555216 32767
i changed the *** *** line to the following to get what I initially expected:
a[i][j] = get_int("Pls provide values for matrix: ");
intended actual result after change:
1 2 3
4 5 6
My question is what is the meaning/Where did the originally printed values come from? Is this something to do with the memory? My guess is that in the first run I printed values from an array that does not exist? Thank you any answer or even advice for further reading would be greatly appreciated
CodePudding user response:
My question is what is the meaning/ Where did the originally printed values come from?
It comes from reading from the int a[2][3] which is uninitialized. Doing so makes your program have undefined behavior. You could initialize it to get all 0's instead: int a[2][3] = {0};
get_int reads one int so the input prompt you provide is misleading. You can't enter all 6 values at once. Input them one by one:
for (i = 0; i < 2; i )
{
for (j = 0; j < 3; j )
{
a[i][j] = get_int("Please provide a value for [%d][%d]: ", i, j);
}
}
Making this change also makes in more obvious to the user that the input fails when trying to enter all six at once. The prompt is then repeated to signal to the user to try again.
