Some questions about pointers

I am in my third year of high school and am currently learning C ++. Since we did everything we needed to know about programming in general (loops, operators, functions, structures, arrays and two-dimensional arrays), we started binary / text files, and I thought that while we were studying files that study memory management. First of all, I'm trying to learn pointers now, because if I understood correctly, in OOP they are mandatory. Secondly, I like to know how the computer works, what is 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 message stating that the stack around the variable "y" was damaged. If I'm not confused, the stack is dynamic memory, and the heap is static memory, thinking that I get this error because the y variable is not in memory when the program shuts down. Am I on the right track?

Also one more question. I cannot 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 just do this:

int main()
{
    int number = 10;
    number = 15;
    cout << number << endl;
}

Why should I use a pointer? Also, I don’t understand why, if I create a char * and assign it, for example “hello”, it writes hello, not h. Basically, by declaring char *, I declare an array with an unknown size, right? Please tell me what he is doing.

+4
2

, , , "y" .

>> char*, . , x. >> , , x .

, std::string :

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

cin.

. , . ( ++ ), , std::string, , : a char* , , >> . , char* , .

+5

y char: . , , "" char. , , "" , , .

, y char, :

char* y = new char[50]; // Create an array of 50 chars, on the HEAP, not the stack

char y[50]; // Create an array of 50 chars, on the STACK, not the heap.

STACK . , , . 50 , , . .

HEAP . , , . , , "" (). , , , .

, , 50 . () . , : .

x. x , . x . x () , .

. , - . , . , . char *y = new char[50], , y.

() , , " ": , . .

, , , : . : " ". delete [] y , .

, - : x , , , : , , - ( ) , . .

- " ". , , .

+2

Source: https://habr.com/ru/post/1539321/


All Articles