gpt4 book ai didi

c - char *str 和 char str[] 之间的区别

转载 作者:行者123 更新时间:2023-12-02 06:18:49 25 4
gpt4 key购买 nike

我将相同的字符串值分配给一个指针和一个char 数组

char *str = "hello" "world";  
char str1[] = "hello" "world";

然后使用sizeof()函数返回它们的长度

sizeof(str);     //  on my computer, it's 8 !!
sizeof(str1); // return 11, which is right

但是它们都可以被 %s 打印出来:

printf("%s\n%s\n", str, str1);

那么为什么 sizeof(str); 会返回错误的值?

最佳答案

So why does sizeof(str);return a wrong value ?

不是因为 sizeof 返回其操作数类型的字节大小。来自 C99 标准(草案 n869)的 6.5.3.4 The sizeof operator 部分,第 2 条:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

因此:

sizeof(str)  == sizeof(char*)
sizeof(str1) == sizeof(char[11])

关于c - char *str 和 char str[] 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17484370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com