Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.9k views
in Technique[技术] by (71.8m points)

c - Why am I getting Unhandled exception thrown: read access violation

I do not understand what is happening.

I made a program to get a char input and output it back. I receive this exception every time I press enter to input a value into the program:

Unhandled exception thrown: read access violation. this->_format_it was 0x38.

I have tried a large arrangement of inputs and it seems that no matter what I input it will throw this at me. In fact, This is almost exactly the code my college gave me

Here is the code:

// Card Value
// cardValue.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
    char rank = 'c';

    printf("Enter the card rank : ");
    scanf("%c", &rank);
    printf(rank);

    return 0;
}

Removing the address operator will result in another exception:

Unhandled exception at 0x79B498F1 (ucrtbased.dll) in Card Decks.exe: 0xC0000005: Access violation writing location 0x00000063.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

printf(rank); is incorrect, as printf() does not accept a single char as input like that.

In C++, this code would not even compile at all. But in C, the compiler will implicitly convert an integral value into a pointer, and char is an integral type.

The read Access Violation error is complaining about memory address 0x38 being read from. 0x38 is the ASCII code for the character '8', is that the value you are inputting?

The 1st parameter of printf() must be a char* pointer to a null-terminated format string, eg:

printf("%c", rank);

All of the examples in the code your college gave you are in this similar form.


If you remove the & on the scanf("%c", &rank) call (why?), you get an Access Violation writing to memory address 0x63, because the value of rank gets implicitly converted as-is to a pointer. 0x63 is the ASCII code for the character 'c', which is what you are initializing rank to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...