我是c++的新手,为什么在第一种情况下工作,而不是在遮罩char*中的一个字符后的第二种情况

I am new to c++ why is casting working in first case but not in second cout after masking one of the characters in char*

本文关键字:char 一个 二种 情况 字符 工作 一种 为什么 新手 c++ 情况下      更新时间:2023-10-16

为什么在屏蔽了char*

中的一个字符后,cast在第一种情况下工作,而在第二种情况下不工作?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
   int n = 10;
   char* ch = (char*) calloc(6, sizeof(*ch));
   ch = strdup("ab");
   cout << strlen(ch) << endl;
   int* p = (int*) ch;
   cout << (char*)p << endl;// works fine it prints "ab" 
   *p = *p & 65280;
   cout << "cast not workingt" << (char*)p << endl; // it does not work  here
   free(ch);      
   return 0;   

}

写成十六进制,65280就是0x0000FF00。因此,在int为4字节的普通系统上,您将ch[0]设置为0。这是一个空终止符,因此当您尝试打印字符串时,将看到一个空字符串。

注意:写入*p会导致未定义的行为,因为写入也超过了分配区域的末尾;strdup("ab")分配3个字节。在普通系统上,这可能不会产生不良影响,因为堆分配是在一定大小的块中完成的。

相关文章: