sizeof array with pointer

Source: Internet
Author: User

When learning pointers, we get the definition of pointers and the definition of arrays, but at this point it is curious that the pointer is just an address, and that the array is the same as the pointer, and how does sizeof know its length?

So Baidu has the following reply:

Never think of array names as pointers, although sometimes they are interlinked, but only for some time.

sizeof is a fancy function that tells you that you may not believe that--sizeof has determined the results of sizeof at compile time, which is a bit like macro.

char str[] =  "Hello"  ; sizeof  (str )  = 6 
When the compiler compiles, it is fully known from the context that STR is an array of,sizeof  (str )  = 6  is, of course, the number of bytes in the array, This number of bytes can be determined during compilation (the size of the array must be specified before compilation, C language)

Void *p = malloc ( 100 ); sizeof  (  p )  = 4  the
compiler sees p as a pointer, but who can guarantee the size of the memory that the pointer refers to? Although you write here 100, but malloc is dynamically assigned, no one can guarantee that malloc will return 100 bytes, even if you do not call malloc, call a function that you write, the compiler is not in the compile time to determine the size of the pointer memory, And sizeof must know the result during compilation, well, sizeof had to return the size of the memory that the pointer itself occupies, 32 bytes on the 4-bit machine, and 8 bytes on the 64-bit machine.



void func  ( char str[100])  
{ sizeof ( str )  =  4 }  When an
array is used as a parameter, the compiler compiles to pointers during compilation, so that although you define STR as an array, it is actually equivalent to:
void func  in the compiler's eye (  CHAR * STR)  
{ sizeof ( str )  = 4 } 
Remember that when an array is a parameter, are compiled as pointers by the compiler.

sizeof array and pointer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.