Surya Teja Vemparala
Surya Teja Vemparala

Reputation: 499

What is the difference in pointing a 1-D array and 2-D array?

When I run this code :

#include<stdio.h>
int main()
{
     int a[2]={1,2};
     printf("%d \t %d",*(a+1),a[1]);
}

It outputs : 2 2

Next I used two dimensional array for the same problem but it is giving me errors.

#include<stdio.h>
int main()
{
     int a[2][2]={{1,2},{3,4}};
     printf("%d \t %d",*(a+1),a[1][0]);
}

My idea here is to point the address of (a+1) and print its content.But it is giving Wrong Format error. But When I point it to *(a+1) i.e, when I use * ( *(a+1)),it is printing the content.

Why does the program doesn't print the content when pointed to (a+1)? What is the difference in pointing a 1-D array and 2-D array?

Upvotes: 1

Views: 80

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

When I run this code [...] It outputs : 2 2

This is because expressions *(a+1) and a[1] are identical: square bracket expressions in C work by adding their operands together (i.e. a and 1 in your case) and then dereferencing the result.

I used two dimensional array for the same problem but it is giving me errors.

This is because *(a+1) is of the same type as an element of a. When a is a 1D array of int, its elements are ints. When a is a 2D array of int, its elements are 1D arrays of int. In your second example you are trying to pass a 1D array of int to printf with the format specifier that expects a single int, which causes an error.

My idea here is to point the address of (a+1) and print its content.

Then you need to add one more level of dereference (i.e. one more asterisk) to "counter" the 1D array:

printf("%d \t %d",**(a+1),a[1][0]);
//                 ^

demo.

An expression to get a[1][1] is slightly more complex:

printf("%d \t %d",*(*(a+1)+1),a[1][1]);

demo.

Upvotes: 2

user4520
user4520

Reputation: 3457

A 2D array is implemented as an array of arrays; thus, in the second case, you're trying to printf a pointer (a[1], not a[1][0]). If you dereference that pointer, it will work:

printf("%d \t %d", **(a + 1), a[1][0]);

Upvotes: 1

Related Questions