What is the meaning of the following?
int sampleArray[] = {1,2,3,4,5};
I understand that the sampleArray
now points to the first element of the array.
However, what does it mean whe开发者_StackOverflow中文版n I say &sampleArray
? Does it mean I am getting the address of the sampleArray
variable? Or does it mean a two-dimensional array variable?
So, can I do this:
int (*p)[5] = &sampleArray?
No, sampleArray
does not really point to the first element of the array. sampleArray
is the array.
The confusion arises because in most places where you use sampleArray
, it will be replaced with a pointer to the first element of the array. "Most places" means "anywhere that it isn't the operand of the sizeof
or unary-&
operators".
Since sampleArray
is the array itself, and being the operand of unary-&
is one of the places where it maintains that personality, this means that &sampleArray
is a pointer to the whole array.
The name of an array evaluates to its address (which is the address of its first element), so sampleArray
and &sampleArray
have the same value.
They do not, however, have the same type:
sampleArray
has a type ofint*
(that is, a pointer-to-int)&sampleArray
has a type ofint (*)[5]
(that is, a pointer to an array of five ints).
int (*p)[5]
declares a pointer p
to an array of five int
s. Ergo,
int (*p)[5] = &sampleArray; // well-formed :)
int (*p)[5] = sampleArray; // not well-formed :(
As usual, the comp.lang.c FAQ already explains this stuff:
- So what is meant by the ``equivalence of pointers and arrays'' in C?
- Since array references decay into pointers, if arr is an array, what's the difference between arr and &arr?
You probably should read the whole section on arrays and pointers.
Some sample code:
#include <stdio.h>
int main()
{
int a[] = {1,2,3,4,5};
int (*p)[5] = &a;
//Note
//int (*p)[5] = a; // builds (with warnings) and in this case appears to give the same result
printf( "a = 0x%x\n" , (int *)a);
printf( "&a = 0x%x\n", (int *)(&a));
printf( "p = 0x%x", (int *)p);
return;
}
The output - same for both ways.
$ ./a.exe
a = 0x22cd10
&a = 0x22cd10
p = 0x22cd10
Compiler
$ gcc --version gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) Copyright (C) 2004 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
that is called insilization of an array. array is collection of similar type of data like int,char,float number like that.
精彩评论