#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 < 4000 && !StringEqual(given[i-1], "end"); i++)
{
given[i] = GetLine();
/*
if (sizeof(given[i]) > sizeof(longest))
{
longest = given[i];
}
*/
printf("%lu\n", sizeof(given[i])); //this ALWAYS RETURNS EIGHT!!!
}
printf("%s", longest);
}
为什么它总是返回8 ???
答案 0 :(得分:13)
C中没有string
数据类型。这是C ++吗?或string
是typedef?
假设string
是char *
的typedef,您可能想要的是strlen
,而不是sizeof
。使用sizeof
得到的8实际上是指针的大小(到字符串中的第一个字符)。
答案 1 :(得分:6)
它将它视为一个指针,指针的大小显然是你机器上的8bytes = 64位
答案 2 :(得分:4)
你说“不要担心这个 - &gt; lib我写道”但这是关键信息,因为它定义了字符串。假设字符串是char *,并且机器上的字符串大小为8.因此,sizeof(给定[i])是8,因为给定[i]是一个字符串。也许你想要strlen而不是sizeof。
答案 3 :(得分:2)
这是字符数组本身和指向数组开始位置的指针之间的常见错误。
例如C风格的字符串文字:
char hello[14] = "Hello, World!";
是14个字节(消息为13个,空终止字符为1个)。
您可以使用sizeof()
来确定原始C样式字符串的大小。
但是,如果我们创建一个指向该字符串的指针:
char* strptr = hello;
尝试使用sizeof()
找到它的大小,它只会返回系统上数据指针的大小。
因此,换句话说,当您尝试从字符串库中获取字符串的大小时,您实际上只获得指向该字符串开头的指针的大小。您需要使用的是strlen()
函数,它以字符形式返回字符串的大小:
sizeof(strptr); //usually 4 or 8 bytes
strlen(strptr); //going to be 14 bytes
希望这可以解决问题!