类型转换长指针问题

kam*_*mal 1 c c++

  char *sBuffer=new char[20];
    char * sStringStart = sBuffer;

    long * plMsgStart = (long *) sBuffer;// what is this line doing

    long i=500;

    *plMsgStart = i // what is this line doing
Run Code Online (Sandbox Code Playgroud)

最后一行是否在char数组中分配500?但是当我打印数组时,我得到了垃圾值

嘿,下面的人是实际的代码,我在将代码从c ++转换为c#时遇到了它,下面的代码是c ++函数的一部分,现在为什么下面的函数会给出垃圾值?

char *sBuffer=new char[20];
char * sStringStart = sBuffer;
BSTR bsMsgBody= SysAllocString(L"Helo");
sStringStart+=4;
long * plMsgStart = (long *) sBuffer;

long l=50;

*plMsgStart=l;

sprintf(sStringStart, "%S", bsMsgBody);

printf("%S",sBuffer);
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 6

那是演员.它说"我知道我在做什么,我想把char*它视为一个long*".然后,它分配i给第一个元素(相当于plMsgStart[0] = i;.

根据大小long,您将覆盖char数组中的前4个或8个元素.打印它仍然是未定义的行为,因为sBuffer它不是以null开头的.

如果你这样做了

 char *sBuffer=new char[20]();
Run Code Online (Sandbox Code Playgroud)

然后尝试打印sBuffer(在long覆盖之后),您将看到对应于二进制表示的4(或8)个字符500.

视觉

 char *sBuffer=new char[20];

 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 | | | | | | | | | | | | | | | | | | | | |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

 long * plMsgStart = (long *) sBuffer;

 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |       |       |       |       |       |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                 ^^^^^
    note this is still the same memory,
   but "seen through the eyes" of a long*


 *plMsgStart = 500;

 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |  500  |       |       |       |       |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Run Code Online (Sandbox Code Playgroud)

  • 我认为整个事情是UB,因为它违反了类型别名规则.也许还有对齐问题...... (2认同)