'C programming, printing 2D array using for loop, cs50
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 get_int() 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
