I'm at third year of high school and I'm studying C++ at the moment. Since we have done everything that we needed to know about programming in general (loops, if statements, functions, structs, arrays and bidimensional arrays) we started binary/text files and I thought that while we learn files learning memory management. First of all, I'm trying to learn pointers now because, if I understood correctly, in OOP they are a must. Second, I like to know how a computer works, what's behind what's happening. Now, I made this small piece of code
int main()
{
char y;
char *x;
x = &y;
cout << "Write a word: ";
cin >> x;
cout << x << endl;
system("pause");
return 0;
}
And it works, but when the program shuts down I get an error that says stack around the variable 'y' was corrupted. If I'm not confused, the stack is the dynamic memory and the heap is the static memory, thinking about that I'm getting this error because the variable y is not in the memory when the program shuts down. Am I on the right path?
Also, one more question. I can't understand when and why I should use pointers, for example:
int main()
{
int number = 10;
int* pointer;
pointer = &number;
*pointer = 15;
cout << *pointer << endl;
system("pause");
return 0;
}
Why can't I simply do this:
int main()
{
int number = 10;
number = 15;
cout << number << endl;
}
Why should I use the pointer? Also, I don't understand why if I create a char* and assign it, for example "hello" it writes hello and not h. Basically, by declaring a char* I declare an array with unknown size, right? Please tell me exactly what it does.