I'm new to using C++ and wonder - why is using pointers necessary? Especially since it's seemingly so easy to lose track and create a memory leak.
Why use pointers in programming?
I'll mention two main benefits:
1- Memory benefits
Because a pointer is simply an address in memory, they consume almost no memory of their own. The data you need is probably already in memory as it is, so if you use standard variables, you’re basically creating a copy of that data that is already stored in memory and now you’re dealing with twice as much memory as you should be. Pointers prevent this by simply showing you where you can find your data and letting you deal with it directly.
2- Dynamically allocating memory:
Pointers can be dynamically allocated and this gives them a huge benefit over standard variables. With a standard variable, you have to know exactly how much memory you’re going to need to allocate while your programming it!
Reply:If you've got some huge data structure, it's a lot more efficient to pass a pointer to it to some procedure or function instead of creating a local copy of the entire thing.
Reply:It allows you to think about things the way the computer has to. It helps you have a better concept of computers and programming.
"int a = 3;" on the compiler level is actually a pointer to a memory address that contains the value 3.
Reply:Yes, you might create a memory leak. But on the other side you can allocate the memory as YOU want and need to. So manually allocating memory by pointers might be more efficient.
Reply:1.used for calling by reference in functions..
2.dynamic memory allocation
3.while using strings
eg; char s[10]="striihjgl";char *p="fjdafhkd";
char s1[10];char *p1;
s1=s; is error
but p1=p; is possible...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment