pointer & array conflict
let
int*p ,b = 5;
p = &b;
denotes a ONE DIMENSIONAL array, then what is the output given by following statement
printf("%d",p);
开发者_如何学JAVA
is it an address? if it is an address then tell me which element it belongs,please explain clearly
p = &b
This doesn't denote an array! As I explained here, they're not the same thing. b
is just an integer value. If you declare b
as int b[] = {1, 2, 3};
then p
will point to b
's first element.
printf("%d",p);
This will print p
's value, and since p
is a pointer and points to b
, this will print b
's address. printf("%d", &b);
will give the same result.
By the way, if b
was an array, b[5]
would be translated into *(p + 5)
, so you can read (and write) values by adding the number of elements to the beginning of the array. And b[5] == p[5] == *(b + 5) == *(p + 5)
!!! But not because arrays and pointers are the same thing, just because an array's name translates to its first element's address.
As a side note, compilers always use pointers notation (*(base + offset)
) when compiling to assembly.
The p
pointer does not denote a one-dimensional array. It is simply a pointer to an integer. It may point to the first element of an array, like when you do int* p = new int[6]
, but that's something entirely different; in that case you allocate space for a new array of six integers and you store the address of the first one (or, the beginning of the array) in p
.
If you print p
it will print the memory address it stores. If p
"denotes an array" (emphasis on quotes) then you will print the address of the first element of the array.
int*p ,b = 5;
p = &b;
is exactly equivalent to:
int b = 5;
int *p = &b;
p ends up being a pointer to int. Now its true that this code will have much the same effect on what ends up in p (although b has a completely different type and value) as this:
int b[1] = {5};
int *p = b; // or int *p = &b[0];
certainly in either case p points to an int which you may treat as a simple int, or as the first (and only) element in a one-dimensional array of size one. So, what follows is legal and gives meaningful results in both cases:
printf("%d is stored at %p\n", *p, p);
printf("%d\n",p[0]);
but that's pretty much where the similarity ends.
address of the first element of the array. (if b was an array) use p++ to scroll through the array
精彩评论