1

I test the length/size of char array, pointer and string as below code.
Why sizeof(pArray) is 8? I guess it is a pointer which should be 4.
Why sizeof(str) is 8 instead of 6 or 7?
Why sizeof("abcdef") is 7 instead of 6?

char array1[10] = {'a', 'b'};
char array[10] = "abcdef";
const char * pArray = "abcdef";
string str = "abcdef";
printf("array1:%d, array:%d, pArray:%d, str:%d,strsize:%d, strlen:%d,  raw:%d\n", sizeof(array1), sizeof(array), sizeof(pArray), sizeof(str), str.size(), str.length(), sizeof("abcdef"));

Program output:

array1:10, array:10, pArray:8, str:8,strsize:6, strlen:6,  raw:7
3
  • 2
    What is string? Is it just a typedef of char*? Anyway, pointers can be 8 bytes too (this is probably a 64-bit environment). Commented Apr 23, 2015 at 16:43
  • 1
    Who told you that a pointer size has to be 4? Do you know \0 ? Do you want the memory buffer size, the byte size of the content, the count of visible characters...? Commented Apr 23, 2015 at 16:44
  • 1
    Is your system 32 or 64 bit? Commented Apr 23, 2015 at 16:45

2 Answers 2

6
  • sizeof(array1) is 10 because you declared it with 10 elements.
  • sizeof(array) is also 10 for the same reason;
  • sizeof(pArray) is 8 maybe because you are in a 64 bit machine, so 8 bytes = 64 bit;
  • As the sizeof(str) is the size of the class structure, you'll get the size of the only internal pointer, that in your case is 8 bytes (because you are in a 64-bit machine, this can change from platform to platform too);
  • str.size() and str.length() returns the same - it's the length of the string itself;
  • sizeof("abcdef") is 7 because constant strings in C always get the implicit character '\0' at the end to terminate properly, so it is 1 more byte in your string (6 + 1 = 7);
Sign up to request clarification or add additional context in comments.

1 Comment

The size of a structure may actually be larger than the size of the single element, as there may be padding after the element (padding before is forbidden, however). This might be the case on some 32 bit architectures for example, where structs are 64 bit aligned because of the 64 bit data bus. For 64 bits systems, this may be similar for cache-lines. So, you never should use the size of an element to get the address of the next in a struct; use offsetof() instead.
2

The size of a pointer depends on the architecture. If compiled on a x64, it will be 8, on a 8/16 bit CPU, it may be 16 (less is very uncommon). A string constant will always get an implicit "\0" at the end to terminate the string properly. Therefore be careful when assigning a string const to a fixed size array!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.