sizeof(char*)做什么?

Chr*_*Bui 2 c++

我正在阅读c ++ Primer,这个代码片段出现了,我想知道sizeof(char*)做了什么,为什么它如此重要?

 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);
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Ana*_*tts 8

因为否则你将获得字数组占用的字节数,而不是元素数(在英特尔架构上,char指针是4或8字节)


fre*_*sch 6

sizeof(char*)返回系统的指针大小.sizeof(words)返回数组中的字节数.由于数组中的每个元素都sizeof(char*)很大,因此元素的数量是number_of_bytes/bytes_per_element,所以sizeof(words)/sizeof(char*).