下面的代码编译正确,但是执行时, 控制台显示以下错误...异常代码:c0000005。 错误发生在以下行:
*cptr++ = hextbl[((tval >> 4) & 0x0F)];
此错误与内存访问不当有关。 这样,我相信错误可能是我仍然做的事情 对指针和算术的理解不正确......
#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);
}
感谢您的帮助! :)
最佳答案
您的指针:
char *bufASCII;
未初始化。然后你写它:
*cptr++ = x;
您需要先初始化它,否则使用它是未定义的行为。例如:
char *bufASCII = new char[2];
尽管如此,这:
bufASCII = put_hexbyte(bufASCII, val);
会丢失你原来的指针。如果您想要缓冲区末尾的返回值,您应该存储该单独的值:
char* eob = put_hexbyte(bufASCII, val);
关于c++ - C/C++ 语言 - 指针和算术...异常代码 : c0000005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28351073/