C – > sizeof字符串总是8

#include "usefunc.h" //don't worry about this -> lib I wrote int main() { int i; string given[4000], longest = "a"; //declared new typdef. equivalent to 2D char array given[0] = "a"; printf("Please enter words separated by RETs...\n"); for (i = 1; i  sizeof(longest)) { longest = given[i]; } */ printf("%lu\n", sizeof(given[i])); //this ALWAYS RETURNS EIGHT!!! } printf("%s", longest); } 

它为什么总是返回8 ???

C中没有string数据类型。这是C ++吗? 或者string是typedef?

假设stringchar *的typedef,你可能想要的是strlen ,而不是sizeof 。 你用sizeof获得的8实际上是指针的大小(到字符串中的第一个字符)。

它将它视为一个指针,指针的大小显然是你机器上的8bytes = 64位

你说“不要担心这个 – > lib我写的”但这是关键信息,因为它定义了字符串。 假设字符串是char *,并且机器上的字符串大小为8.因此,sizeof(给定[i])是8,因为给定[i]是字符串。 也许你想要strlen而不是sizeof。

这是字符数组本身和指向数组开始位置的指针之间的常见错误。

例如C风格的字符串文字:

 char hello[14] = "Hello, World!"; 

是14个字节(消息为13个,空终止字符为1个)。 您可以使用sizeof()来确定原始C样式字符串的大小。

但是,如果我们创建一个指向该字符串的指针:

 char* strptr = hello; 

并尝试使用sizeof()找到它的大小,它只会始终返回系统上数据指针的大小。

因此,换句话说,当您尝试从字符串库中获取字符串的大小时,您实际上只是获得指向该字符串开头的指针的大小。 你需要使用的是strlen()函数,它以字符forms返回字符串的大小:

 sizeof(strptr); //usually 4 or 8 bytes strlen(strptr); //going to be 14 bytes 

希望这可以解决问题!