learning about C++

hi i am a beginner and we just started learning about pointers, and my question is "Why pointers are important and what are the precautions that I should keep in mind while using pointers in C/C++".
Last edited on
just learn you will find them , when the time come you will know them

some of them that i know

Always initialize them
Check the bounds (size of pointer offset / index)
free the memory when done
Set to NULL after freeing
Last edited on

Why pointers are important

Why are array indices important?

Pointers are just another way for your program to express indirection -- in other words, to access something without using it's name. You use indirection when accessing some element of an array: my_array[22];.

So in a way, pointers are a bit like array indices. But they're more versatile, since you don't need to have an array around to use them. They let you access things that your program doesn't own, or needs to share between programs or between modules of the same program.

Suggestions:
-- Initialize your pointer to nullptr (prefer this over NULL since C++11)
-- Once the pointed to resource is dead, set your pointer to nullptr.
-- Keep track of the owner of the pointed-to-resource
Rules:
-- Make sure the pointed-to resource is alive when you access it;
-- Follow the strict pointer aliasing rules.

Maybe there's more but I can't remember.

Note:
In modern C++ (since 2011) there are two standard facilities called unique_ptr and shared_ptr, AKA "smart pointers". You should be using these, instead. They're a little bit more complicated, but much harder to break.

Note:
Please avoid writing "C/C++" again. C is not interchangeable with C++, and the differences between the languages are only increasing with time. Best practice in C is not the same thing as best practice in C++. The above note describes one such difference.
Topic archived. No new replies allowed.