什么时候printf("%s",char*)停止打印?

use*_*406 15 c printf

在我的课上,我们正在编写自己的C的malloc()函数副本.为了测试我的代码(当前可以分配空间很好)我正在使用:

char* ptr = my_malloc(6*sizeof(char));
memcpy(ptr, "Hello\n", 6*sizeof(char));
printf("%s", ptr);
Run Code Online (Sandbox Code Playgroud)

输出通常是这样的:

Hello
Unprintable character
Run Code Online (Sandbox Code Playgroud)

有些调试认为我的代码本身并没有造成这种情况,因为ptr的内存如下:

[24个字节的元信息] [请求的字节数] [填充]

所以我认为printf正在进入填充,这只是垃圾.所以我进行了测试: printf("%s", "test\nd");得到:

test
d
Run Code Online (Sandbox Code Playgroud)

这让我想知道,当DOES printf("%s",char*)停止打印字符时?

Jam*_*lis 30

它在到达空字符(\0)时停止打印,因为%s期望字符串为空终止(即,它期望参数为C字符串).

字符串文字"test\nd"以null结尾(所有字符串文字都以null结尾).ptr但是,您的字符数组不是因为您只将六个字符复制到缓冲区(Hello\n)中,而您不复制第七个字符 - 空终止符.


Dav*_*har 5

当它到达null字符时,James对于printf停止是正确的,并且Uri是正确的,你需要分配一个7字符的缓冲区来保存"hello \n".

如果您使用通常的C语言来复制字符串strcpy(ptr, "Hello\n"),那么与终结符的一些混淆会减轻:而不是memcpy.

另外,根据定义,C中的sizeof(char)== 1,因此6*sizeof(char)是多余的

  • 它不仅仅是一种新的架构,而是一种新的语言.如果`sizeof(char)!= 1`,则不再使用C编程.http://stackoverflow.com/questions/2215445/are-there-machines-where-sizeofchar-1 (4认同)
  • 6*sizeof(char)可能是多余的,但在我看来,这是一个很好的做法,原因很简单(1)如果某个新架构上的字符不是= 1或(2)此代码被移植到wchar_t ... . (2认同)