LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C - why pointers? (https://www.linuxquestions.org/questions/programming-9/c-why-pointers-4175524475/)

szboardstretcher 11-05-2014 03:24 PM

C - why pointers?
 
Pointers, variables, addresses, etc...

I've been a hobby C programmer for years, but I never quite got to understand pointers.

Don't misunderstand me,. I know how to write out a pointer, and the language behind it:

Code:

int variable1 = 78;
int *pointing;
pointing = &variable1;
printf("value of variable1: %d\n", *pointing);

But I have NO idea why that is useful, or why i would need to use it. I look at it and say 'Great, I defined variable1, stored the address of it in *pointing, and printed out the value pointed to by *pointing.'

Then I further think this: "Why didn't I skip all of that and just write this..."

Code:

int variable1 = 78;
printf("value of variable1: %d\n", variable1);

Any gifted C programmers that can explain in stupid-people terms what pointers are used for and why I need them? Tia!

suicidaleggroll 11-05-2014 03:32 PM

Easiest/simplest reason is that C functions are pass by value. When you define a variable "a" and set it to "5", and then pass variable "a" to a function, the function doesn't get the variable "a", it gets the number "5". If the function changes what it received to "6" and then returns, your calling routine will still have a value of "5" for "a". It is impossible for the function to modify your variable "a" when you pass by value.

If instead you pass the memory address of "a", and your function pulls it in as a pointer, then any changes it makes will affect your original variable.

dugan 11-05-2014 03:43 PM

You also need pointers to do dynamic memory allocation.

szboardstretcher 11-05-2014 03:45 PM

Thanks for the great explanation. That's the first time in years that I've thought to ask about it, and I'm glad I did.

Ty. ty.

dugan 11-05-2014 03:46 PM

Quote:

Originally Posted by szboardstretcher (Post 5265176)
Thanks for the great explanation. That's the first time in years that I've thought to ask about it, and I'm glad I did.

Ty. ty.

In that case, I think you'll benefit this from this: :)

http://stackoverflow.com/a/5754

dyates3 11-05-2014 03:46 PM

Nailed it, Mr. Roll
 
Yep, pointers allow you to "Pass by reference (address)". The other two options are "Pass by value" and declaring the variable as a global (which is generally a bad thing).

When you use a pointer, the actual "physical" address of the variable is used. (The quotes are because of compiler/OS stuff about blocking direct access to memory.TMI)

If you don't use a pointer, then the compiler will create a different physical address (therefore different variable) and store the contents(value) of the first variable in it.

NB Pointers can crash a system.
NB2 Arrays of pointers and pointers into structures require strong drink and profanity.

don

Birdski 11-05-2014 04:29 PM

Quote:

Originally Posted by suicidaleggroll (Post 5265167)
Easiest/simplest reason is that C functions are pass by value. When you define a variable "a" and set it to "5", and then pass variable "a" to a function, the function doesn't get the variable "a", it gets the number "5". If the function changes what it received to "6" and then returns, your calling routine will still have a value of "5" for "a". It is impossible for the function to modify your variable "a" when you pass by value.

If instead you pass the memory address of "a", and your function pulls it in as a pointer, then any changes it makes will affect your original variable.

This has been one of the simplest / best explanations I have ever seen for this! Kudos to you! I wish I had come across this explanation when I was first learning c.

Brad

metaschima 11-05-2014 05:29 PM

They exist in C because C is close to hardware e.g. assembly. In assembly you can do the same things you can with pointers. They are essential for memory access.

a4z 11-06-2014 01:02 AM

take 6 minutes for this
www.youtube.com/watch?v=-n8FP7Ncq8A

rtmistler 11-06-2014 08:09 AM

It's an interesting question; one that I guess experienced C programmers don't think about much because over time it becomes intuitive.

Obviously for the stack this is important. If you have a structure, array, or string which is large, you don't pass a copy of that structure through your call stack, you instead pass the address of it. This therefore reduces the stack size requirements.

Many of the systems I've worked with pass large volumes of data, and as a result they contain hardware assists such as shared memory or direct memory access (DMA) features which rapdily transit large buffers of data through the system. For instance a network router will have hardware assist which detects packets at the various layers of communications. As a result, much of the exposed information is actually address information which is transitted from call function to call function. The packet headers are really repeated addresses from the hardware pool of available header structures. The code doesn't make assumptions about the "flow" of header addresses even if it is found that they become deterministic, instead the code knows that header structures are of a certain pre-defined form and so one address value is handed from the hardware to the driver, and then subsequently to each next piece of software down the chain until the packet is finally handed back to the hardware for further transit. As a result, much of the body of the data is relatively untouched or even not-manipulated at all by software. Technically speaking, one cannot "pass" the actual data, they would have to make a copy of it, but that also would be working against the intentions of the hardware, and in the end any modifications you'd make to a packet or header in a software copy would then need to be copied back to the hardware variation anyways.

Library manipulations of data are done via pointers, memcmp, memcpy, etc.

Pointers are useful for processing multi-dimensional arrays and even transcending data types. Say you have a large body of data which contains records of one type, with each record further containing sub-structures of other various types, as well as multiple entries. Like phone book entry. The top level is one type of structure. Within there are sub-structures for multiple groups of phone numbers, email addresses, and physical addresses. So to step through a contact list, the first level would use a pointer to step through the higher layered structure, and then another pointer based off of "sub-entry[0]" from within a given top level structure would be capable to step through the list of those sub-entries. For something like a linked list, you'd have a *next pointer as part of the list. That value could be true, or it could be NULL indicating that you are at the end of the list.

That reminds me of sorting items in a list. Sure if they're just numbers, then what's the big deal right? But if they're phone book entries and hence lengthy or complicated structures, what's most important about the sort spec? Alphabetism usually. And does it matter where, or how, or in which order they are physically stored in memory? Likely since they've been written to NV (non-volatile) memory, where they're stored permanently; then their physical locations are irrelevant so long as they're known. However the organization and processing of "the list" is then also done by reference. "Pointer to first", "Pointer to next", "Pointer to previous". And when you insert Michael Myers into an already lengthy list, that entry gets stored physically in the next available NV storage location, but what happens with the list is that the alphabetical entry just before that name gets told the next entry (by address) is now this new one. This new entry's "last" pointer gets set up properly. And the entry just alphabetically after this new entry gets it's pointers updated.

So rather than re-do memory to accomodate the fact that you've added an entry to the list, the list uses pointers to define the list. And likewise when you change your sort spec; like you'd do with a file folder list, the programming part of it re-arranges the sorting of the list pointers versus moves anything around.

When I mentioned earlier about "transcending data types"; it's not always the intended way, but I'm sure it's done a lot. Data arrives in a structure, the form of that structure is known, perhaps some sub-component of it is important, and that may be referenced as part of the structure, but there are times when someone abstracts the structure of a sub-component of it to be like a (char *) so that they can just look at the individual characters for a specific purpose. Again, a convenience done by casting the structure, and what better way to do that than to just refer to the original copy, then get or manipulate what you need too and then move on.

NevemTeve 11-06-2014 09:28 AM

A much simpler approach: Exactly how did you use 'scanf' so far?

mina86 11-06-2014 11:26 AM

Quote:

Originally Posted by metaschima (Post 5265226)
They exist in C because C is close to hardware e.g. assembly. In assembly you can do the same things you can with pointers. They are essential for memory access.

This is very misleading description in my opinion. Arguably Java is not close to hardware, yet, it has pointers… (They are called references and you cannot to arithmetic on them, but they are pointers). You could go even higher and say that Python has pointers. Trying to hide the fact that pointers are everywhere only creates confusion.

metaschima 11-06-2014 11:56 AM

I didn't know Java and Python had pointers. I've tried python in the past, but they were never mentioned. Either way, in assembly you work with memory addresses and with data stored at those addresses. Higher level languages emulate this because it is efficient.

NevemTeve 11-06-2014 12:04 PM

High-level languages hide the pointers from you, but the pointers are still there.

a4z 11-06-2014 12:06 PM

at the end all programming languages have to point at some locations in memory / somewhere else
some think that programmers should not know about this details and try to hide this facts, with often not so good effects.

that's why I posted to the link to Stepanov short talk, even if it's about Stroustrup and C++, because he mentions how useful it is to be close on the hardware.
And he mentions addresses and why he loves them


All times are GMT -5. The time now is 06:13 AM.