Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding output of pointer size in C Programming Language

I am trying to understand why this printf statement gives two different outputs; I think I have a decent understanding of one of the outputs.

Here is the code:

    const char *ptr = "hello";
    const char array[] = "hello";

   //Question 2
   
    printf("%zu %zu\n", sizeof(ptr),sizeof(array));

Now I understand why sizeof(array) returns six: this is because the length of "hello" is 6 plus an additional null terminator.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I do not understand why sizeof(ptr) is 8; my guess is that all memory addresses in C occupy 8 bits of memory hence the size is 8. Is this correct?

>Solution :

The C language, itself, doesn’t define what size a pointer is, or even if all pointers are the same size. But, yes, on your platform, the size of a char* pointer is 8 bytes.

This is typical on 64-bit platforms (the name implies 64-bit addressing which, with 8 bits per byte, is 64/8 = 8 bytes). For example, when compiling for a Windows 64-bit target architecture, sizeof(char*) is 8 bytes; however, when targeting the Windows 32-bit platform, sizeof(char*) will be 4 bytes.

Note also that the "hello" string literal/array is 6 bytes including the nul terminator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading