简体   繁体   中英

array's base address

I was going through a book where I found this question

Does mentioning the array name gives the base address in all the contexts?

Can some one explain the cases where array name does not give the base address.thanks

Array-to-pointer decay does not happen everywhere. One example is the argument of sizeof , another is the argument of & :

int arr[10];

sizeof(arr);          // gives 10 * sizeof(int), NOT sizeof(int*)

int (*p)[10] = &arr;  // gives the address of the array, NOT of an rvalue

The second example is fairly obvious, since the value of the array-to-pointer decay is not-an-lvalue, so it wouldn't make sense any other way.

C 2011 online draft

6.2.3.1 Lvalues, arrays, and function designators

3 Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type '' is converted to an expression with type ''pointer to type '' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So, given a declaration like

int a[N];

the following expressions do not convert the expression a to a pointer type:

sizeof a
_Alignof a
&a

Given the following declarations

char str[] = "This is a test";
char *p    = "This is another test";

the string literal "This is a test" is being used to initialize an array of char , so it will not be converted to a pointer expression; instead, the contents of the array will be copied to str . In contrast, the string literal "This is another test" is not being used to initialize an array, so it is converted to a pointer expression, and the value of the pointer is written to p .

sizeof运算符就是这样一种上下文,其中sizeof(array)给出sizeof(array)的(字节)大小。

Array name give address of first element:

int a = {1,2,3};

Suppose address of a is 12

printf(" %u %u",a,&a);

result is

12 12

Where a is address of first element and &a is address of array. same value but different semantic

printf(" %u %u", a+1, &a+1);

result is

14 18

a increased by 2 because 'a' is address of integer and a+1 increase by 2 that is sizeof(int)

where as &a+1 increate by size of array that is 3 int = 3 * sizeof(int)

Assuming sizeof int is 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM