ju**********@yahoo.co.in writes:
[...]
I also want to know how can we return a pointer to first element
of a 2-d array ? what would be the declaration for such a function
(the function that returns the pointer to the first element of
a 2d array whose elements are of type int) ?
For eg. suppose I have a 2d array
int arr[3][4];
I want to return the address of first element of arr.
Can I do
return(arr);
But then what would be the decalaration of such a function (I mean the
return type ?) will it be "int *" or "int **" ?
What exactly do you mean by the "first element" of a 2d array?
Strictly speaking, C doesn't have 2-dimensional arrays; it has arrays
of arrays. Given
int arr[3][4];
the first element of arr is an array, not an int.
A two-dimensional array can also be implemented as an array of
pointers, or as a pointer-to-pointer, rather than as an array of
arrays. This is more flexible, since it allows you to vary the size
of the subarrays (but you have to keep track of it).
Confusingly, given:
int x[10][10];
int (*y)[10];
int **z;
and assuming memory has been allocated properly, all of the following
are valid expressions of type int:
a[0][0]
b[0][0]
c[0][0]
but they all have different meanings.
If you want to return a pointer to its first element, use
return &arr[0];
The type is pointer-to-array-of-3-int
If you want to return a pointer to the first element of the first
element, which is of type int, use:
return &arr[0][0];
Both of these can be transformed if you like, since x[y] is equivalent
to *(x+y).
But in general, pointers to arrays are rarely useful. The pointed-to
array type must be of fixed size, the syntax is confusing, and
whatever you're trying to do can usually be done more easily with a
pointer to the first element, rather than a pointer to the entire
array.
Another thing: given "int arr[3][4];", the type int** isn't going to
be useful. int** is a pointer to a pointer; the array declaration
doesn't create any pointer objects for an int** to point to.
Arrays are not pointers. Pointers are not arrays. C's syntax almost
seems designed to fool you into forgetting this.
If you haven't read section 6 of the C FAQ (Arrays and Pointer), read
it. If you have, read it again.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.