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

问题描述 投票:0回答:2
#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 sizeof string-concatenation strlen
2个回答
0
投票
  1. strcat(strp,strq);
    调用未定义的行为,因为
    strp
    不够大,无法容纳连接的字符串。此操作的结果无法预测。

  2. 永远不要使用

    sizeof
    来获取字符串长度。
    sizeof(x)
    为您提供字节大小
    x

尝试同样的方法

char strp[100] = "hello";

始终使用

strlen


0
投票

sizeof
运算符告诉您其操作数类型的大小(以字节为单位)。由于
strp
的类型为
char [6]
,因此它的大小为 6。因此它没有给出
wrong
答案,它只是没有告诉您您认为它是什么。

但是,此代码存在一个更大的问题,即您要附加到

strp
中包含的字符串,但没有空间容纳任何其他字符。结果,你写到了数组末尾,触发了未定义的行为

strcat
的目的地必须有足够的空间来存储连接的字符串

© www.soinside.com 2019 - 2024. All rights reserved.