字符串连接在 C 中使用 sizeof() 无法正常工作,但它适用于 strlen() [duplicate]

String concatenation not working properly in C using sizeof() but it works for strlen() [duplicate]

提问人:Priyanka Govindarajan 提问时间:9/16/2023 更新时间:9/16/2023 访问量:43

问:

#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 给出正确的答案?

c 字符串 连接 的大小 strlen

评论


答:

2赞 0___________ 9/16/2023 #1
  1. strcat(strp,strq);调用未定义的 bahaviour,因为它不够大,无法容纳连接的字符串。此操作的结果无法预测。strp

  2. 永远不要用于获取字符串长度。 给你的大小以字节为单位。sizeofsizeof(x)x

尝试相同的方法char strp[100] = "hello";

始终使用strlen

  1. printf("%d", ... (两者)在使用错误的格式时调用未定义的行为。它必须是针对类型的%zusize_t

该程序演示了 和 之间的区别:strlensizeof

int main(void) {
    char strq[] = " world";
    char strp[1000] = "hello";

    strcat(strp,strq);
    puts(strp); //hello world
    printf("sizeof(strp) = %zu ",sizeof(strp));
    printf("strlen(strp) = %zu",strlen(strp));
    return 0;
}

结果:

hello world
sizeof(strp) = 1000 strlen(strp) = 11
4赞 dbush 9/16/2023 #2

运算符告诉您其操作数类型的大小(以字节为单位)。由于 has type(即刚好足够大以存储其启动器,因为您没有给出明确的大小),因此它的大小为 6。所以它不是给出答案,它只是没有告诉你你认为它是什么。sizeofstrpchar [6]wrong

但是,此代码存在一个更大的问题,即您正在附加到其中包含的字符串中,但没有空间容纳任何其他字符。因此,写入超过数组末尾,从而触发未定义的行为strp

的目标必须有足够的空间来存储连接的字符串。在这种情况下,长度必须至少为 12 个元素。strcatstrp