简体   繁体   English

C Memset输出

[英]C Memset output

#include <stdio.h>
#include <string.h>

int main() {
  char* p = new char[10];
  memset(p,0,10);
  printf("%c",*p);
}

I suppose memset set every byte starting p to 0 . 我想memset将每个从p开始的字节设置为0 I'm a little surprised to see nothing at all printed out. 我一点都没看到打印出来的东西,感到有些惊讶。 What on earth was happening for memset ? memset到底发生了什么?

memset does set all the bytes to 0; memset确实将所有字节设置为0; thus, when you dereference p , you get a char with value 0 (the NUL byte), and on most systems, printing such a char produces no visible output. 因此,当取消引用p ,则得到一个char具有值0(NUL字节),并且在大多数系统,打印这样的char不产生可见的输出。 If you want to print the numeric value of the byte instead, use printf("%d", *p); 如果要打印字节的数值,请使用printf("%d", *p); .

ANS: 0 (int data) is typecasted to equivalent char (ASCII) and then copied on all 10 arrays of memory. ANS: 0(int数据)被类型转换为等效的char(ASCII),然后复制到所有10个内存数组中。 Coincidently the equivalent of 0 (int) to char is null character `'\\0'. 巧合的是,与char等效的0(int)是空字符''\\ 0'。 So, nothing is shown on the screen. 因此,屏幕上什么也没有显示。 Logically we can say that null is printed in screen. 从逻辑上讲,我们可以说在屏幕上打印了null。

{ie; (char)0 is equivalent to '\0' (null character)}

EXPLAINATION: 说明:

memset(p,0,10);

Observer the second parameter 0, which is an integer (of 2 bytes), however the memset() will have to set the 0 data in each byte array of p. 观察第二个参数0,它是一个整数(2个字节),但是memset()必须在p的每个字节数组中设置0数据。 How 2 byte integet can be copied on 1 byte memory space? 如何在1个字节的存储空间上复制2个字节的integet? This is not possible. 这是不可能的。

So, memset() method firstly typecast the int data to char (1 byte) and then writes the char(1 byte) to each byte of that memory array. 因此,memset()方法首先将int数据类型转换为char(1个字节),然后将char(1个字节)写入该内存阵列的每个字节。

Note: memset() will not put any null character at the end of string. 注意:memset()不会在字符串末尾放置任何空字符。 So we have to do it explicitly. 因此,我们必须明确地做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM