C/C++ 语言 - 指针和算术...异常代码:c0000005

C/C++ language - POINTERS and ARITHMETIC... Exception Code: c0000005

下面的代码编译正确,但是在执行时, 控制台显示以下错误...异常代码: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);

会丢失原来的指针。如果你想要缓冲区末尾的 return 值,你应该存储 separateyl:

char* eob = put_hexbyte(bufASCII, val);

这个:

char *bufASCII;    // pointer to store these ASCII

是一个指向字符的指针,但它实际上还没有指向任何东西,因此你不能写入那个指针。