This mig开发者_如何转开发ht be a stupid question, but I have a little problem with understanding of C Pointers. Even more when it comes to arrays. For example:
char ptr[100];
ptr[0]=10;
fprintf(stderr, "&ptr: %p \n ptr: %p \n*ptr: %d\n", &ptr, ptr, *ptr);
if ( &ptr == ptr ) {
fprintf(stderr, "Why?\n");
}
How is this even possible? 'ptr' is at the adress &ptr. And the content of ptr is the same as &ptr. Then why is *ptr = 10 ???
The address of the first element of the array is the same as the address of the array itself.
Except when it is the operand of the sizeof
or address-of &
operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be implicitly converted ("decay") to type "pointer to T" and the value will be the address of the first element in the array.
If the expression a
is of type "N-element array of T", then the expression &a
is type "pointer to N-element array of T", or T (*)[N]
.
Given the declaration
T a[N];
then the following are all true:
Expression Type Decays to ---------- ---- --------- a T [N] T * &a T (*)[N] n/a *a T n/a
The expressions a
and &a
both evaluate to the same value (the location of the first element in the array), but have different types (pointer to T and pointer to array of T, respectively).
ptr
(which, as sbi says, is really an array) decays to &(ptr[0])
(char *
to first element)
This is the same address as &ptr
(a char (*) []
), even though they are different types.
int arr[5];
arr[0]= 7;
fprintf(stdout,"%p %p %d",&arr[0],arr,*arr);
if( (int)&arr == (int)arr ) printf("good\n");
else printf("bad\n");
return 0;
}
This will work....
精彩评论