Why am I getting Unhandled exception thrown: read access violation

-1

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.

c
exception
visual-studio-2019
asked on Stack Overflow Jan 19, 2021 by Carson Fujita-Turnbull • edited Jan 19, 2021 by Carson Fujita-Turnbull

2 Answers

4

printf()'s first argument must be a pointer to a format string, not a char. You could do

printf("%c", rank);
answered on Stack Overflow Jan 19, 2021 by Michael Galassi
2

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.

answered on Stack Overflow Jan 19, 2021 by Remy Lebeau • edited Jan 19, 2021 by Remy Lebeau

User contributions licensed under CC BY-SA 3.0