tags:

views:

208

answers:

2

I was reading through the c++ Primer and this code snippet came up and I was wondering what does the sizeof(char *) do and why is it so significant?

 char *words[] = {"stately", "plump", "buck", "mulligan"};

 // calculate how many elements in words
 size_t words_size = sizeof(words)/sizeof(char *);

 // use entire array to initialize words2
 list<string> words2(words, words + words_size);

Thanks in advance.

+8  A: 

Because otherwise you would get the number of bytes that words array takes up, not the number of elements (char pointers are either 4 or 8 bytes on Intel architectures)

Paul Betts
Thanks for your quick answer, I thought sizeof returned the number of elements not the number of bytes.
L1th1um
2-byte pointers are also possible, on some Intel architectures.
John Millikin
+7  A: 

sizeof(char*) returns the system's pointer size. sizeof(words) returns the number of bytes in the array. Since each element in the array is sizeof(char*) big, the number of elements is number_of_bytes/bytes_per_element, so sizeof(words)/sizeof(char*).

fre.sch