Reputation:
I am newbie in C programming.I want to print 2 as my first element is 2 in the 2D array.But as i knew that n holds the first address of the array so *n should print the first element that is 2.My code
#include <stdio.h>
int main()
{
int n[3][3]={2,4,3,6,8,5,3,5,1};
printf("%d\n",*n);
return 0;
}
why it is printing an address.Can anyone explain it to me??
Upvotes: 0
Views: 106
Reputation: 1346
I think that you got some warning on %d
because you are not tried to print the value - just the address only.
For a 2D array, to get any value, you need to dereference twice. i.e **n
.
*n
is also suitable, but for a 1D array.
Here you can use either **n
, *n[0]
or n[0][0]
instead of *n
.
Upvotes: 1
Reputation: 74615
You need to declare your array like this:
int n[3][3]={{2,4,3},{6,8,5},{3,5,1}};
Note that the first [3]
isn't necessary (but there's nothing wrong with specifying it). By the way, if you enable warnings, e.g. with gcc -Wall
, the compiler will warn that there are missing braces in your initialiser.
Then to print the first value you can use:
printf("%d\n",n[0][0]);
Or, if you prefer:
printf("%d\n",*n[0]);
You have an array or arrays, so this takes the zeroth element (which is an array), then dereferences it to get the zeroth value.
Upvotes: 1
Reputation: 3870
If you have an 1D array-
int n[9]={2,4,3,6,8,5,3,5,1};
printf("%d\n",*n);
Because If you dereference the 1D array it will fetch the element. Now It will print 2. But
int n[3][3]={2,4,3,6,8,5,3,5,1};
It is a 2D array so you need to dererence two times. If you dererence one time it will fetch the address of the array only. n
, n[0]
, *n
, &n
, &n[0]
all will represent the starting address of it.
Try -
printf("%d\n",**n);
or
printf("%d\n",n[0][0]);
Upvotes: 0
Reputation: 122383
A 2d array is just an array of arrays, so *n
is actually the first subarray, to print the first element of the first subarray:
printf("%d\n", **n);
Or this is simpler and more clear:
printf("%d\n", n[0][0]);
Upvotes: 1
Reputation: 75707
If n
would have been an array of integers, *n
would have printed the first integer, as you are expecting.
But n
is not that. Is a 2-dimensional array. One way of looking at it would be: an array of arrays. So in fact *n
is an array.
Upvotes: 0