I'm new to programming in C and i found something i don't understand:
When initializing an array without given values, i thought all elements would be zero. I wrote this few lines of code...
int main()
{
int obj[10][4];
for (int a = 0; a < 10; a++)
{
print("%d\t%d\t%d\t%d\n", obj[a][0], obj[a][1], obj[a][2], obj[a][3]);
}
}
...and was pretty confused by its output:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 7661
7960 2697 2260 7960
1551630361 -2130960380 146780176 -2130960380
I don't understand why some of the values are zero and some are not. I was even more confused that this numbers change when i add more code. For example, i changed the previous example and added another print()...
int main()
{
int obj[10][4];
print("start\tstop\tcenter\tdist\n\n");
for (int a = 0; a < 10; a++)
{
print("%d\t%d\t%d\t%d\n", obj[a][0], obj[a][1], obj[a][2], obj[a][3]);
}
}
...getting this:
start stop center dist
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 7673
7972 2709 2272 7972
1551630361 -2130960380 146780176 -2130960380
Using a bigger array, this numbers are not only found at its end. The first few values are always zero, but then "something" happens.
I've found a solution here at SO, using memset(), that works for me, but... what's going on here?
Could someone explain this, using words a C-newbie would understand?
valgrindrun. This may give hints to you where the bug is (uninitialized variables are fairly well detected by valgrind).valgrindand bookmarked some sites i might understand after using C a little longer ;-)-gto your compiler invocation (You probably typegcc -Wall -std=c99 my_file.c -o my_binaryright now, so this becomesgcc -g -Wall -std=c99 my_file.c -o my_binary). Second step: instead of executing like this:./my_binary, you dovalgrind ./my_binary. And that's it. If there is "... uninitialized value...", there's also the file and line listed there and you can look into the problem. Just try it with the code of your question!