Welcome to Qi-U Community for programmer and developer-Open, Learning and Share

Categories

0 votes
1.4k views
in Technique[技术] by (31.9m 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

Please log in or register to answer this question.

1 Answer

0 votes
by (31.9m 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...