#include <stdio.h>
int main(void) {
char strp[] = "hello";
char strq[] = " world";
strcat(strp,strq);
puts(strp); //hello world
printf("%d",sizeof(strp)-1);//this gives 5(length of 'hello' -1 for '\0')
printf("%d",strlen(strp));//gives correct answer(11)
return 0;
}
为什么在这种情况下 sizeof 给出错误的答案而 strlen 给出正确的答案?
strcat(strp,strq);
调用未定义的行为,因为 strp
不够大,无法容纳连接的字符串。此操作的结果无法预测。
永远不要使用
sizeof
来获取字符串长度。 sizeof(x)
为您提供字节大小 x
。
尝试同样的方法
char strp[100] = "hello";
始终使用
strlen
sizeof
运算符告诉您其操作数类型的大小(以字节为单位)。由于 strp
的类型为 char [6]
,因此它的大小为 6。因此它没有给出 wrong
答案,它只是没有告诉您您认为它是什么。
但是,此代码存在一个更大的问题,即您要附加到
strp
中包含的字符串,但没有空间容纳任何其他字符。结果,你写到了数组末尾,触发了未定义的行为。
strcat
的目的地必须有足够的空间来存储连接的字符串