I've two source code, the difference between the codes is the 2d array size.
My question is simple: Why causes runtime error the first code and why running ok the second code?
First code:
1 2 3 4 5 6 7 8 9
#include <stdio.h>
int main(){
int t[5][5];
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
scanf("%d",t[i][j]);
}
}
}
Second code:
1 2 3 4 5 6 7 8 9
#include <stdio.h>
int main(){
int t[10][10];
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
scanf("%d",t[i][j]);
}
}
}
Compiler: Dev-Cpp 4.9.9.2 - Default Compiler
I know that the correct form is scanf("%d",&t[i][j]), but I'cant understand why.
When I passing the simple array the correct form is scanf("%d",t[i]), because this to pass into *(t + i) and this is a pointer.
Would sombody explain what happened if passing a 2d array to scanf()?
My question is simple: Why causes runtime error the first code and why running ok the second code?
Luck.
I know that the correct form is scanf("%d",&t[i][j]), but I'cant understand why.
So why not use the correct form?
The & means "address of", so the following applies:
1 2 3 4 5
int a;
int* ptr_to_a = &a;
*ptr_to_a = 42;
printf( "Value of a == %d == %d\n", a, *ptr_to_a );
printf( "Address of a == %ul == %ul\n", (unsignedlong)&a, (unsignedlong)ptr_to_a );
The reason scanf() wants addresses is so that it can know where to put the data it reads.
1 2 3
scanf( "%d", a ); /* fails. 42 is an invalid address. */
scanf( "%d", &a ); /* succeeds: the address of 'a' is a valid address */
scanf( "%d", ptr_to_a ); /* succeeds: again, scanf() gets a valid address */
The use of an array doesn't change the need to get the address of its elements for scanf().