Is there a difference between &array[0] and &array when passed to a C Function. This array is a void* array which currently takes integer as data.
Added the
Assuming array
is declared
void *array[N];
then the expressions &array[0]
and &array
will yield the same value (the address of the first element of the array is the same as the address of the array itself), but will have different types.
Expression Type
---------- ----
&array void *(*)[10] -- pointer to 10-element array of `void *`
&array[0] void ** -- pointer to pointer to void
Your function prototype will need to match up with whichever expression you pass. If you call the function as
func(&array);
then the function prototype needs to be
void func(void *(*arrp)[10]) {...}
If you call the function as
func(&array[0]);
then the function prototype needs to be
void func(void **arrp) {...}
although in that case you should pass the size of the array as a separate parameter.
Now, assuming array
is declared
void **array = malloc(sizeof *array * N);
then the expressions &array
and &array[0]
will yield different values and different types.
Expression Type
---------- ----
&array void ***
&array[0] void **
&array
will give you the address of the array
variable itself, which is different from the address of the heap memory that's been allocated for the array. Again, your function prototype will need to match up with the type of the expression you use.
Yes, there's a big difference, and it depends on context.
Consider this:-
char arrayA[10];
char *arrayB;
&arrayA[0]
and &arrayB[0]
both have type char *
.
But &arrayA
has type char (*)[10]
while &arrayB
has type char **
- the address of the pointer.
For arrayA
, these point to the same address - but for arrayB
, they do not! There's a common C misconception that "pointers and arrays are the same". This is a great example of where they are absoluelty not,
See this : http://ideone.com/OcbuXZ
Yes there is a big different
&array[0]==>void**
AND
&array==>void***
This won't compile, you are using a void *
and try to get the first element of it. But what size does it have? The compiler doesn't know. Using int *
may compile, if you are not trying something like this:
int main (void) {
int *arr = malloc( 10 );
arr = &arr[0]; // this is ok
arr = &arr; // wrong data type
}
&array
returns an int **
, &array[0]
returns int *
. These are different data types.
If array
is really an array, then
&array[0]
is the pointer to element 0 of array[]
&array
is the pointer to the entire array[]
So, these two expressions are of different types. And that's the main difference that may cause your code to fail to compile if you pass the wrong one of the two.
At the low level, however, the two pointers are going to hold the same address.