下面的代码编译正确,但是当它执行时,控制台显示以下错误...例外代码:c0000005.错误发生在以下行:
*cptr++ = hextbl[((tval >> 4) & 0x0F)];
Run Code Online (Sandbox Code Playgroud)
此错误是关于不正确的内存访问.这样,我相信这个错误可能是我对指针和算术仍然不理解的东西......
#include <stdio.h>
// function prototypes
int main(int argc, const char *argv[]);
char *put_hexbyte(char *cptr, char tval);
// main routine
int main(int argc, const char *argv[]) // variables to get arguments
{
char val = 65; // 0x41 >>> I need 2 bytes 0x34 and 0x31,
// they are ASCII from 0x41 (0x34 = "4" and 0x31 = "1")
char *bufASCII; // pointer to store these ASCII
bufASCII = put_hexbyte(bufASCII, val);
return 0;
}
// Put a byte as hex ASCII, return pointer to next location.
char *put_hexbyte(char *cptr, char tval)
{
static char hextbl[16] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
printf("at this point, all is OK!!!\n"); // <<< OK!
*cptr++ = hextbl[((tval >> 4) & 0x0F)]; // <<< memory violation error! (Exception Code: c0000005)
*cptr++ = hextbl[tval & 0x0F];
return(cptr);
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!:)
你的指针:
char *bufASCII;
Run Code Online (Sandbox Code Playgroud)
没有初始化.然后你写信给它:
*cptr++ = x;
Run Code Online (Sandbox Code Playgroud)
您需要先将其初始化,否则使用它是未定义的行为.例如:
char *bufASCII = new char[2];
Run Code Online (Sandbox Code Playgroud)
虽然那时候,这个:
bufASCII = put_hexbyte(bufASCII, val);
Run Code Online (Sandbox Code Playgroud)
会失去原始指针的踪迹.如果你想要缓冲区末尾的返回值,你应该存储那个单独的:
char* eob = put_hexbyte(bufASCII, val);
Run Code Online (Sandbox Code Playgroud)