Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about pointers

Tags:

c++

pointers

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.

like image 311
user3605299 Avatar asked Mar 20 '23 16:03

user3605299


1 Answers

when program shuts down I get an error that says stack around the variable 'y' was corrupted

Because >> responds to a char* by accepting an entire string. The pointer must point to a large enough buffer to hold that string, but it only points to the stack variable x. >> doesn't know that, so it just charges ahead and writes over whatever is next to x on the stack.

Actually, you'd better use std::string in this case:

std::string s;
std::cin >> s;

reads a word from cin.

Why can't I simply do this

You can. You don't need pointers in this simple program, but you will need them for more advanced stuff. Even if you don't use them a lot (modern C++ has many facilities to replace strings by safer and easier constructs), it still helps to know that std::string, for example, is implemented using pointers: it's really a char* wrapped in a class that takes care of things like >> for you. The class knows where the char* points and adjusts it if it needs more space to store extra characters.

like image 198
Fred Foo Avatar answered Mar 27 '23 16:03

Fred Foo