I am new in C++ and I've started to learn last night
I need help with the following error:
Unhandled exception at 0x0F828F0E (ucrtbased.dll) in Hello World.exe: 0xC0000005: Access violation writing location 0x00000002.
My code so far:
#include <iostream>
#include <conio.h>
#include <stdio.h>
using namespace std;
int main() {
cout << "CUMPARATURI" << endl;
int mere = 3 + 1;
int banane = 16 / 4;
cout << endl;
cout << "Avem " << mere << " mere" << endl;
cout << "Avem " << banane << " banane" << endl;
int a = 16, b = 18;
cout << endl;
cout << "Valoarea lui a este " << a << endl;
cout << "Dati o valoarea noua lui a : "; cin >> a;
cout << "Noua valoarea a lui a este : " << a << endl;
cout << endl;
cout << "Acesta este primul rand \nAcesta este al 2-lea \nAcesta este al 3-lea";
cout << endl;
printf("\nAceasta este valoarea lui a: %d ", a);
printf("\nLocatia lui a este %d \nDa-i valoare noua lui a : ", &a);
scanf_s("%d", a);
printf("Noua valoare a lui a este : %d",a);
_getche();
return 0;
};
If you take a look at the scanf_s
documentation, you'll see that the variables you want to read data into are written after a &
. The &
takes the address of the variable, in fact scanf_s
needs to know where to write the result in memory.
So, you should fix your code like this:
// Note '&a' instead of 'a'
scanf_s("%d", &a);
That said, in C++ you may want to consider std::cin
for reading data into variables, e.g.:
int a{};
std::cin >> a;
Note that in this case there's no need to use the &
(address-of) operator.