Click here to Skip to main content
15,887,302 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

double input1 = 1.1;

int main()
{
    double celsius1, kelvin1, rankine1;
    scanf ("%g", input1);
    celsius1 = (input1 - 32) * (5 / 9);
    kelvin1 = (input1 + 459.67) * (5 / 9);
    rankine1 = (input1 + 459.67);
    printf("%g degrees Fahrenheit\n%g degrees Celsius\n%g degrees Kelvin\n%g degrees Rankine", input1, celsius1, kelvin1, rankine1);
    return 0;
}

This code is saying "Exception thrown at 0x7AB06582 (ucrtbased.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x9999999A."when I attempt to enter an input at the scanf line. I have to use %g for the assignment but cannot tell why it is not working within this code.

What I have tried:

I've tried adding & in front of the variables akin to some examples online, however more build errors began to show up.
Posted
Updated 13-Jul-20 20:03pm
v2

You need to write
scanf ("%g", &input1);
to pass the address of your variable to scanf. Elsewhere, you're referencing values, so no & is needed or wanted.
 
Share this answer
 
Comments
CPallini 14-Jul-20 2:02am    
5.

Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type.
There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.
These arguments are expected to be pointers: to store the result of a scanf operation on a regular variable, its name should be preceded by the reference operator (&)


You only need the '&' in front of input1 on scanf because it takes memory addresses not values like printf. Adding it anywhere else in this code would cause errors.

Some more material on pointers below. It's an important topic to understand in C++.
Pointers - C++ Tutorials[^]
Pointers in C/C++ with Examples - GeeksforGeeks[^]

EDIT:
The reason you get that error is because scanf is trying to use the value of input1 (1.1) as a memory address (0x9999999A). Your code doesn't own that memory so is getting an access violation.
 
Share this answer
 
v2
Comments
CPallini 14-Jul-20 2:02am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900