Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

c - Why sizeof(array) and sizeof(&array[0]) gives different results?

#include <stdio.h>
int main(void){
    char array[20];

    printf( "
Size of array is %d
", sizeof(array) );  //outputs 20
    printf("
Size of &array[0] is %d
", sizeof(&array[0]); //output 4
}

Code above gives 20 for sizeof(array) and 4 for sizeof(&array[0]).

What I knew was instead of giving array as a argument, its first element can be passed. Shouldn't they give same output as 20? and why &array[0] gives 4 as result? char is stored in 1 byte as far as I know?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the expression sizeof array, array is not converted to a pointer type.

C11, § 6.3.2.1 Lvalues, arrays, and function designators

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.

Therefore, its type is char[20], not char *. The size of this type is sizeof(char) * 20 = 20 bytes.

C11, § 6.5.3.4 The sizeof and _Alignof operators

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.

&array[0] type is char *. That's why the sizeof(&array[0]) gives the same result as sizeof(char *) (4 bytes on your machine).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...