2d array and scanf() problem

Hi!

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()?

Thanks: Beni

Sorry for my poor english! :)
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", (unsigned long)&a, (unsigned long)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().
1
2
      scanf( "%d", &t[i][j] );


Hope this helps.
Last edited on
The reason scanf() wants addresses is so that it can know where to put the data it reads.


Yes, I know it.

t[i] ---> *(t+i), and this is an address.

The use of an array doesn't change the need to get the address of its elements for scanf().


t[i][j] ---> *(*(t+i)+j), and this is an adress.

I know it badly?

I say thank you for the help!
No, that is where you are mixed up.

t[i] == *(t+i) : is not an address. It is an element of t.

&t[i] == (t+i) : this is an address.

The difference is that in the first the address is dereferenced, or resolved to the thing to which it points.

Don't feel badly, pointers mix everyone up at first. Other than that, your code is beautiful: it is well-organized and to the point.

I love your use of English too. :-)
Topic archived. No new replies allowed.