14 Replies - 1343 Views - Last Post: 24 June 2012 - 12:22 PM Rate Topic: -----

#1 natecat  Icon User is offline

  • D.I.C Head

Reputation: 53
  • View blog
  • Posts: 225
  • Joined: 19-December 11

Pointers or variables?

Posted 20 June 2012 - 10:43 PM

I am trying to learn C++ and I am wondering, is it better coding practice to use pointers(Variables pointing to a memory location) or just variables
Is This A Good Question/Topic? 0
  • +

Replies To: Pointers or variables?

#2 aresh  Icon User is offline

  • It's a 16-Bit World!
  • member icon

Reputation: 273
  • View blog
  • Posts: 4,163
  • Joined: 08-January 12

Re: Pointers or variables?

Posted 21 June 2012 - 12:26 AM

Actually it depends on your needs. For the most part, variable will work, but at some places, pointers make life easier. So it depends on your needs, and there is no rule.

This post has been edited by aresh: 21 June 2012 - 12:31 AM

Was This Post Helpful? 0
  • +
  • -

#3 busyme12srv  Icon User is offline

  • New D.I.C Head

Reputation: -5
  • View blog
  • Posts: 44
  • Joined: 18-June 12

Re: Pointers or variables?

Posted 21 June 2012 - 02:08 AM

Using variables or pointers depends absolutely on the choice of the coder, but

there are some situations where you would like to use pointers eg. optimizing memory

while creating linked lists. This is because you donot need contiguous memory locations

here as in case of arrays.

Was This Post Helpful? 1
  • +
  • -

#4 DaneAU  Icon User is offline

  • Great::Southern::Land
  • member icon

Reputation: 284
  • View blog
  • Posts: 1,617
  • Joined: 15-May 08

Re: Pointers or variables?

Posted 21 June 2012 - 02:31 AM

The scope of a variable is important in this, how long do you need a variable to stay alive and how many functions will need to mutate that data. How big is an object and does it warrant passing a location as a reference, instance or pointer.

Example as busyme12srv noted data structures such as a LinkedList can be quite large, now if you need to perform some operation would you pass the instance of the LinkedList (large value in memory) or would you simply pass a pointer to the LinkedList to your function. I would pass a pointer.
Was This Post Helpful? 0
  • +
  • -

#5 anonymouscodder  Icon User is offline

  • member icon

Reputation: 126
  • View blog
  • Posts: 710
  • Joined: 01-January 10

Re: Pointers or variables?

Posted 21 June 2012 - 06:23 AM

Pointers are dynamic allocated variables, allocated on the heap memory. 'Variables' are local variables, allocated on the stack memory.

Local
Pros
The memory is automatically freed at end of the scope (no worry about the memory)
Stack memory is faster

Cons
The memory is alive only in the given scope
Easier to overflow it (Exceed the stack size)


Dynamic
Pros
The memory is alive until you deallocate it (or for the whole program execution)
Harder to overflow it

Cons
You have to manually deallocate it
Heap memory is slower
Was This Post Helpful? 0
  • +
  • -

#6 jimblumberg  Icon User is offline

  • member icon


Reputation: 4003
  • View blog
  • Posts: 12,354
  • Joined: 25-December 09

Re: Pointers or variables?

Posted 21 June 2012 - 07:14 AM

Quote

Pointers are dynamic allocated variables, allocated on the heap memory. 'Variables' are local variables, allocated on the stack memory.

Really? What about:
int c = 10;
int *cptr = &c;

There are many uses for pointers, they are not just for dynamic memory.

In my opinion you should use a regular variable whenever possible. Use pointers only when absolutely necessary. Prefer passing by reference over passing by pointer whenever possible. Prefer C++ containers, and whenever possible try to encapsulate the use of pointers into classes or structures.

Jim
Was This Post Helpful? 2
  • +
  • -

#7 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1147
  • View blog
  • Posts: 7,132
  • Joined: 07-September 06

Re: Pointers or variables?

Posted 21 June 2012 - 07:33 AM

Another fun thing to keep in mind is that non-dynamic arrays are placed on the stack. Now, this isn't terribly important for an array of 10 items, but when you get to larger things, such as a 3D array of 100 items each, then you will run into a stack overflow (more likely you will just see a segmentation fault).
Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5796
  • View blog
  • Posts: 12,631
  • Joined: 16-October 07

Re: Pointers or variables?

Posted 21 June 2012 - 08:20 AM

View PostBetaWar, on 21 June 2012 - 10:33 AM, said:

but when you get to larger things


This is function of size. If you can compile it and your memory model doesn't choke, then you're reasonably ok. Stack size constraints ain't what they used to be.

View Postanonymouscodder, on 21 June 2012 - 09:23 AM, said:

Heap memory is slower


I would question this.

Ultimately, memory is memory. It is as fast as the hardware it uses. Your program is loaded into RAM, your stack being part of the memory required for the load. When you ask for more memory from the "heap", the address could be right next to you program.

The question of speed is essentially if you have traverse a memory pages to get data. While there is an impact to this, it is so small as to be insignificant.

This post has been edited by baavgai: 21 June 2012 - 08:24 AM

Was This Post Helpful? 2
  • +
  • -

#9 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Pointers or variables?

Posted 21 June 2012 - 09:47 AM

*
POPULAR

Variables vs. Pointers: a Death Match!

First off, a pointer IS a variable, just one that contains a memory address rather than some regular droll data like a social security number... which if you think about it is kind of like a pointer.

So point #1: Pointers ARE variables and so using an int* vs using and int generally uses the same amount of memory (actually a int* may actually be bigger than an int).

So lets see if we can ask some more discerning questions:

Static (local) memory vs Dynamic memory:

that is, which is better to use:
int localArray[100];
int* dynamicArray = new int[100];


While it is generally faster to allocate the localArray it is limited in size (since it sits on the stack) its life-time is limited to the current scope (which can be a good thing since it can avoid memory leaks).

The dynamic array can take a little more time to allocate, and if you forget to free the memory you can have a memory leak.

So the big down side to dynamic memory is the dreaded "memory management" issue -- C++ does not have a nice garbage collector and sometimes the default allocator is not good enough for some developer who writes their own which ends up with bugs in it... and soon they are cursing the project and moving to Java or C#.

NOT to mention you have to use the dereferencing operators! Littering your code with *'s and ->'s! You end up with pointers to pointers to pointers... and one day your find your self writing an expression like:

**(*(table[i].object)->collection)->item->value->name

and you wonder how you got yourself into this mess! Ahhhhhhh pointers! Run away! Run away!

UNFORTUNATELY, pointers have a great deal of value as well, in point of fact modern computing requires them and while other languages may abstract them away for you they are always there. You just need to find ways to "abstract the abstraction" and keep them sane.

So to avoid pointer spaghetti and symbol soup - we can actually bring some of C++ features into use (and stop making C++ into C with classes).

Pass by reference vs Pass by pointer:

Personally I don't like symbol soup so I tend to "pass by reference" by using C++'s references!

void updateObject(obj& arg); vs.
void updateObject(obj* arg);

Of course this changes how you call the functions but in general I find that it reduces the amount of "pointer symbology" inside my functions and I like it!

So wait, C does not have these references -- So:

C pointers vs C++ abstractions:

In C you HAVE to use pointers, you can't get away from it. You need pointers, function pointers, alloc, malloc, and free -- you just can't really do too much without them - Arrays are accessed via pointers! Strings are char arrays, scanf and printf expect pointers for different arguments. You just can't get away from using them.

In C++ you have options:
#1 STL Collections, Using Vector's and other collections can free you from having to manage the malloc/free of arrays.

#2 C++ has references -- which allow you to pass-by-reference rather than "by pointer" -- yes a pointer is still being used "under the hood" but it abstracts it away.

#3 C++ has Smart Pointers -- while still a *kind* of pointer (actually they are objects) smart pointers help manage memory without needing to resort to new/delete.

#4 C++ has iterators -- again while "pointer like" these can be safer to use and can abstract more than just memory locations.

In fact, in high level C++ code there is often no need for pointers! That is not to say it is not important to know about pointers, but you generally don't have to code them if you don't want to.


So who wins the death match?

Pointer are vital to programming, but are dangerous and easy to screw up.

In general try to avoid using pointers if you can use another feature such as a std::string, std::vector or a std::auto_ptr or std::shared_ptr over raw pointers.

you will be using pointers-a-plenty but you will be abstracting them away into managed structures which can help you keep them in line.
Was This Post Helpful? 6
  • +
  • -

#10 anonymouscodder  Icon User is offline

  • member icon

Reputation: 126
  • View blog
  • Posts: 710
  • Joined: 01-January 10

Re: Pointers or variables?

Posted 21 June 2012 - 10:55 AM

View Postbaavgai, on 21 June 2012 - 12:20 PM, said:

View Postanonymouscodder, on 21 June 2012 - 09:23 AM, said:

Heap memory is slower


I would question this.

Ultimately, memory is memory. It is as fast as the hardware it uses. Your program is loaded into RAM, your stack being part of the memory required for the load. When you ask for more memory from the "heap", the address could be right next to you program.

The question of speed is essentially if you have traverse a memory pages to get data. While there is an impact to this, it is so small as to be insignificant.

I always have been taught that, but I don't really know how practical is this.
I know, as example, that CPython is highly heap based.
Was This Post Helpful? 0
  • +
  • -

#11 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2911
  • View blog
  • Posts: 10,083
  • Joined: 08-August 08

Re: Pointers or variables?

Posted 21 June 2012 - 11:20 AM

View PostNickDMax, on 21 June 2012 - 12:47 PM, said:

Pointer are vital to programming, but are dangerous and easy to screw up.

In general try to avoid using pointers if you can use another feature such as a std::string, std::vector or a std::auto_ptr or std::shared_ptr over raw pointers.

you will be using pointers-a-plenty but you will be abstracting them away into managed structures which can help you keep them in line.

View Postjimblumberg, on 21 June 2012 - 10:14 AM, said:

In my opinion you should use a regular variable whenever possible. Use pointers only when absolutely necessary. Prefer passing by reference over passing by pointer whenever possible. Prefer C++ containers, and whenever possible try to encapsulate the use of pointers into classes or structures.

Couldn't agree more! Pointers are worthwhile when you need them, but when you don't they're just adding complexity and most code beyond hello world is complex enough!
Was This Post Helpful? 1
  • +
  • -

#12 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Pointers or variables?

Posted 21 June 2012 - 12:04 PM

View Postanonymouscodder, on 21 June 2012 - 01:55 PM, said:

View Postbaavgai, on 21 June 2012 - 12:20 PM, said:

View Postanonymouscodder, on 21 June 2012 - 09:23 AM, said:

Heap memory is slower


I would question this.

Ultimately, memory is memory. It is as fast as the hardware it uses. Your program is loaded into RAM, your stack being part of the memory required for the load. When you ask for more memory from the "heap", the address could be right next to you program.

The question of speed is essentially if you have traverse a memory pages to get data. While there is an impact to this, it is so small as to be insignificant.

I always have been taught that, but I don't really know how practical is this.
I know, as example, that CPython is highly heap based.


Well there are a couple of reasons why Heap memory may be "slower" than stack memory.

#1 Allocation time. It takes a certain amount of time to allocate blocks of memory -- allocation on the stack is generally just adding to the stack pointer. So if you are allocating/deleting lots of objects the overhead on the heap can add up -- then again, this can often be fixed by using a better allocator dedicated to your needs. For example it is common to have special allocators for classes known to create lots of small one-off objects.

#2 Heap memory is "more likely" to end up swapped out to disk. I don't really know the ins-and-outs of different OS's virtual memory management schemes but I suppose I can see this as true... I don't know enough to talk intelligently about this but it is an argument others have made to me.

#3 Heap memory for small objects is more likely to cause cache misses. The processor usually has chunks of the often used stack in cache, where as object spread about in the heap are likely to not just cause 1 cache miss but multiple. Again I don't know much about processor caching but the argument makes a certain kind of sense to me.

#4 Accessing an object via a pointer can take a couple of extra operations, the base pointer has to be loaded and then some offset added etc. these extra operations add up. Again I don't feel intellectually up to the challenge of analyzing this one either -- I think that processor manufacturers have done a lot to optimize this process.

#4.1 (old) near pointers vs. far pointers - if a near pointer is 16 bits and a far pointer 32 then it takes more to get the far pointer into memory and more to the address. Modern memory models do not tend to use different size pointers (though some do!). <edit>I think this is where a great deal of the *prejudice* against heap allocation comes from - There are a host of "thumb rules for performance" that are no longer strictly true but persist because *once upon a time* they were good advice. I am often guilty of this myself and often use ++i over i++ because I REALLY want that tiny tiny fraction of a second that may or may not even exist with modern compilers</edit>

I am not really prepared to defend any of these arguments but simply present them for discussion.

This post has been edited by NickDMax: 21 June 2012 - 01:53 PM

Was This Post Helpful? 3
  • +
  • -

#13 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5796
  • View blog
  • Posts: 12,631
  • Joined: 16-October 07

Re: Pointers or variables?

Posted 21 June 2012 - 04:38 PM

Great points!

1) Allocation time - Given. One time overhead. Of concern if you're doing it a lot.

2) You ain't going to disk unless you're run out of the faster stuff. If the program is hitting this wall, then the program's stack would be likely to have the same problem when it was loaded. Conversely, a program could have gotten loaded into slower memory and then a heap allocation catches the faster stuff if it's available.

3) Unsure. The actual memory block given via malloc is usually larger that you expect, to round to OS block sizes. Possibly much larger than you expect, if it's tiny. Memory allocation needn't be stupid, though, and programs sometimes just grab a page and work with it until it needs another.

4) Yep, dereferncing will take an operation. Wheter this is more than the variable on the stack will take really depends on the situation.

4.1) Bingo. This is the one people used to get bent about. Really not that big a deal anymore.
Was This Post Helpful? 0
  • +
  • -

#14 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Re: Pointers or variables?

Posted 21 June 2012 - 04:58 PM

Quote

Unsure. The actual memory block given via malloc is usually larger that you expect, to round to OS block sizes. Possibly much larger than you expect, if it's tiny. Memory allocation needn't be stupid, though, and programs sometimes just grab a page and work with it until it needs another.


the size doesn't really effect caching; just usage. the stack is constantly being used, period, so it stays in cache for basically the whole program. heap memory, isn't so lucky; the OS does it's best to optimize cache performance(allocating close to your old allocation, etc...) but it can only do so much. careful performance tweaks and design can mostly solve this issue.

the biggest issue with heap memory is allocation time. people tend not to realize how inefficient allocation is sometimes. you shouldn't worry too much about it(instead use STL containers) but if performance is a goal then limiting allocations is important.

to answer the OP, each has it's place. it's generally best to use data structures that abstract the use of pointers(not to be confused with obfuscating pointers via typedefs). refrences, smart pointers, vectors, maps, etc... all of these can ease your life

This post has been edited by ishkabible: 24 June 2012 - 12:50 PM

Was This Post Helpful? 0
  • +
  • -

#15 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1255
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Pointers or variables?

Posted 24 June 2012 - 12:22 PM

As a quick addition to everything that's already been stated:

Take into account that you lose type safety when handling untyped (void) pointers and the compiler will not be able to check type compatibility for you. Pointers also defeat a number of optimizations the compiler might have otherwise performed on various code blocks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1