Home > Software design >  Understanding output of pointer size in C Programming Language
Understanding output of pointer size in C Programming Language

Time:02-03

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.

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?

CodePudding user response:

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.

CodePudding user response:

Your guess is partially correct. sizeof(ptr) returns 8 because it's the size of a pointer on a typical 64-bit architecture. The pointer ptr is a pointer to a constant character, so its size is 8 bytes on a 64-bit system. The value stored in the pointer is the memory address of the first character in the string literal "hello", so ptr takes up 8 bytes of memory, not 6.

The size of a pointer is platform-dependent and can be different on different architectures. On a 32-bit system, the size of a pointer would typically be 4 bytes.

  • Related