I am pretty new to C++, and while getting started I got stuck on a frustrating problem concerning pointers. Consider the following code:
#include <iostream>
using namespace std;
int main (){
int* mypointer;
*mypointer = 1;
cout << "Whats wrong";
}
It crashes during runtime. I suspect it has to do with the pointer assignment. But after commenting out the cout statement, the program executes. By assigning the pointer as
int* mypointer, myvar;
myvar = 1;
mypointer = &myvar;
the program runs, and I can print the value of the pointer as:
cout << "value of pointer: " << *mypointer;
I draw the conclusion that this would be the correct usage of a pointer.
BUT: Why does the following code execute??:
#include <iostream>
#include <stdio.h>
using namespace std;
int main (){
int* mypointer;
*mypointer = 1;
printf("This works!\n");
printf("I can even print the value mypointer is pointing to: %i",*mypointer);
}
Simply using printf?? I would really appreciate an explanation guys!