[不懂就问] C 语言字符串指针的问题^-^

2015-10-28 20:47:58 +08:00
 raingolee

最近在看 head first c ,发现了书上有个歧义的地方,

因此上来 v2ex.py 请教各位大兄弟,感谢各位现身教学

void testChar(char msg[])
{
    printf("the msg is %s", msg);
    prinff("the msg cost %s bytes", sizeof(msg));
}

char quote[] = "hi iv2ex bro";
testChar(quote);

第二行输出的到底是 4 个字节还是字符串的长度呢?

1762 次点击
所在节点    C
52 条回复
Smilecc
2015-10-28 20:52:16 +08:00
这里的 quote 实际上是个字符数组, sizeof 会返回这个数组所占的字节数
raingolee
2015-10-28 20:56:47 +08:00
@Smilecc 我的编译器同样是返回这个数组所占的字节数,但是 head first c 上 53 页写着返回编译器一个 int 的大小
zhicheng
2015-10-28 20:58:54 +08:00
会 Crash
11
2015-10-28 20:59:32 +08:00
嗯 会 crash
SErHo
2015-10-28 21:00:02 +08:00
@raingolee printf 写成 prinff 了, sizeof 用 %lu 格式,返回指针的大小, 32 位是 4 , 64 位是 8 。
xufang
2015-10-28 21:01:54 +08:00
唉,”小学生“太多了,而楼上这种只给个答案的也是毛病。楼主我建议你自学下汇编,然后把这段代码看下汇编就明白了。记得用 32 位平台。
xufang
2015-10-28 21:02:15 +08:00
...,被插 2 楼
SErHo
2015-10-28 21:03:10 +08:00
@xufang 啥问题都扯上汇编?这是 C 语言的基本常识,和汇编有什么关系。

$ clang -o test test.c
test.c:6:44: warning: sizeof on array function parameter will return size of
'char *' instead of 'char []' [-Wsizeof-array-argument]
printf("the msg cost %lu bytes", sizeof(msg));
^
test.c:3:20: note: declared here
void testChar(char msg[])
^
1 warning generated.

不知道楼主用的是什么编译器。。。
Smilecc
2015-10-28 21:04:16 +08:00
误人子弟了,是我想当然了,说声对不起。
WalkingEraser
2015-10-28 21:05:55 +08:00
数组名作参数会退化为指针,即 4 或 8 。会 crash 是因为第二个格式化输出有问题,应该是%d
raingolee
2015-10-28 21:05:59 +08:00
@zhicheng
@11
你们两个顽皮了,

不好意思呀,写错了函数名

sed -i 's/prinff/printf/g'
raingolee
2015-10-28 21:07:55 +08:00
@SErHo
感谢回答
不好意思呀,写错了函数名
sed -i 's/prinff/printf/g'
--
用的是 gcc ,但是我返回的却是字符串的长度,难道是我姿势错了?
11
2015-10-28 21:08:53 +08:00
@raingolee 写错函数名是不能编译,然后改了后,因为你用的 %s 所以会 crash 。。
xufang
2015-10-28 21:09:15 +08:00
@SErHo 说这话的时候,你先看看自己的答案有没有问题。。。
0ver1oad
2015-10-28 21:10:17 +08:00
如果是 32bit 系统就是 4 ,因为性能考虑,数组作为参数会变为指针
raingolee
2015-10-28 21:13:46 +08:00
@WalkingEraser
@11
@xufang
@0ver1oad

``` c
#include <stdio.h>

void testChar(char msg[])
{
printf("the msg is %s", msg);
printf("the msg cost %d bytes", sizeof(msg));
}

int main()
{
char quote[] = "hi iv2ex bro";
testChar(quote);
}
```

不好意思各位,刚刚着急了一下,现在重新编译了, 32bit 系统,返回的却是字符串的长度,怎么破?
handelxh
2015-10-28 21:20:14 +08:00
sizeof() 出来的是 char 指针的大小,这个问题有什么可讨论的?
raingolee
2015-10-28 21:22:27 +08:00
@handelxh 不是讨论,是我不懂,那答案是?
raingolee
2015-10-28 21:26:22 +08:00
@0ver1oad
head first c 上 59 页写着返回的字符串的大小,到底孰对孰错啊
WalkingEraser
2015-10-28 21:29:20 +08:00
@raingolee vc 和 GCC 都返回的是指针长度的说…

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/231820

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX