Author Topic: [C] Pointers - what is the point?  (Read 25778 times)

0 Members and 1 Guest are viewing this topic.

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
[C] Pointers - what is the point?
« on: July 16, 2018, 06:59:54 pm »
I am completely confused, pointers are just another name for some variable, I have read a couple of explanations and I'm still not getting why I would want to use them  :horse:.
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11248
  • Country: us
    • Personal site
Re: [C] Pointers - what is the point?
« Reply #1 on: July 16, 2018, 07:03:14 pm »
This is a very broad question. In short, the pointer IS a variable that points to some other variable. Not only they are useful, it is practically impossible to program without them.

A pointer can be made to point to some other location at any other place at time. This is a very valuable property.
Alex
 

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #2 on: July 16, 2018, 07:05:55 pm »
but if i am pointing at another variable why not just use the variable?
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11248
  • Country: us
    • Personal site
Re: [C] Pointers - what is the point?
« Reply #3 on: July 16, 2018, 07:07:08 pm »
Because sometimes you don't know what you want to point to at compile time.
Alex
 

Offline rolycat

  • Super Contributor
  • ***
  • Posts: 1101
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #4 on: July 16, 2018, 07:09:45 pm »
Wikipedia provides a very good explanation of what pointers are and why they are useful here:

https://en.wikipedia.org/wiki/Pointer_(computer_programming)
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11248
  • Country: us
    • Personal site
Re: [C] Pointers - what is the point?
« Reply #5 on: July 16, 2018, 07:10:42 pm »
Imagine you have two big arrays with font data: "uint8_t font_a[1024];" and "uint8_t font_b[1024];". The user has a way to select one or the other.

Now you can write all your code like this:
Code: [Select]
  if (selected_a)
    byte = font_a[index];
  else
    byte = font_b[index];

or you can create a pointer and use that:
Code: [Select]
uint8_t *font = selected_a ? font_a : font_b; // This assignment only happens once when the user has changed the selected font

byte = font[index]; // The rest of the code does not care what font is selected, it just uses the provided data.
« Last Edit: July 16, 2018, 07:13:03 pm by ataradov »
Alex
 

Online wraper

  • Supporter
  • ****
  • Posts: 16860
  • Country: lv
Re: [C] Pointers - what is the point?
« Reply #6 on: July 16, 2018, 07:26:52 pm »
but if i am pointing at another variable why not just use the variable?
Try to make a function which does something with array (not single variable within array) without using pointers.
 

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #7 on: July 16, 2018, 07:31:35 pm »
but if i am pointing at another variable why not just use the variable?
Try to make a function which does something with array (not single variable within array) without using pointers.

I've only just specified my first array, it was an easy way of having multiple locations to store values in from each ADC channel and be able to move from channel to channel by incrementing the variable used as an index.
 

Online wraper

  • Supporter
  • ****
  • Posts: 16860
  • Country: lv
Re: [C] Pointers - what is the point?
« Reply #8 on: July 16, 2018, 07:34:35 pm »
but if i am pointing at another variable why not just use the variable?
Try to make a function which does something with array (not single variable within array) without using pointers.

I've only just specified my first array, it was an easy way of having multiple locations to store values in from each ADC channel and be able to move from channel to channel by incrementing the variable used as an index.
I was meaning returning value. When you pass array to function as an argument, you actually pass pointer to array, not array itself. You can also use pointers to variables as arguments and then modify them from within the function.
« Last Edit: July 16, 2018, 07:39:17 pm by wraper »
 

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #9 on: July 16, 2018, 07:39:57 pm »
oh I might need to do that, any reason I can't just use the "array[index]" as a variable ?
« Last Edit: July 16, 2018, 07:41:52 pm by Simon »
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11248
  • Country: us
    • Personal site
Re: [C] Pointers - what is the point?
« Reply #10 on: July 16, 2018, 07:41:28 pm »
Use for what?
Alex
 

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #11 on: July 16, 2018, 07:42:56 pm »
Anything. So I have an array full of ADC readings, I'll need to process them at some point.
 

Offline IonizedGears

  • Regular Contributor
  • *
  • Posts: 248
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #12 on: July 16, 2018, 07:43:00 pm »
Pointers are just variables to store the address in memory in which other variables are stored.

Note that it is a common misconception that arrays are pointers. It is true that an array often decays into a pointer to the first variable stored in said array but there are some key differences between arrays and pointers.

First, a pointer not of the const type (note the difference between a pointer to a const variable and a const pointer to a variable) can be changed to point to another address in memory by simply storing a new address in the pointer variable. An array cannot be set to point to another location in memory and will always decay as a pointer to the first variable in said array. You can still use the decayed pointer address in pointer arithmetic, however.

Second, sizeof on an array will depend on the amount of elements in an array while sizeof on a pointer will return the size of a pointer variable.

Now for the use cases of pointers.

First, they are incredibly useful in cases where you want the called function to change the value of a non-global variable while not having to return a value.

Ex)

int main(void) {
   int x = 3;
   Int val = 2;

   setVariable(&x, val);
}

void setVariable(int* x, int newVal) {
    *x = newVal;
}

This example is too simple to actually warrant the its use but imagine how it might be useful for more complicated math routines.

Second, it's also really useful for speed and memory concerns. C is ALWAYS pass by value i.e. the parameters of a called function are always different from those that were used in it's call. Changing the value of newVal in the called function in the example above does not change the value of val in the main function because newVal is a new variable that was initialized on the call of setVariable. Things tend to get slower and slower as more and larger variables are sent as parameters to functions. This is especially critical in heavy programs or limited resource environments like embedded systems.

Pointers make things easier by sending one measly pointer  which will be initialized as a pointer in the called function that points to the same address because the value of the pointer (the address in memory of what is being pointed to) is what is passed. Arrays are good for this. The other type that pointers are useful for are structs which are basically just wrappers/envelopes for mutliple variables. Look them up if you aren't familiar, they're useful.

IX
« Last Edit: July 16, 2018, 08:04:37 pm by IonizedGears »
I am an EE with interests in Embedded, RF, Control Systems, and Nanotech.
 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11882
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #13 on: July 16, 2018, 07:43:30 pm »
I've only just specified my first array, it was an easy way of having multiple locations to store values in from each ADC channel and be able to move from channel to channel by incrementing the variable used as an index.

Actually, in C arrays and pointers are two sides of the same coin.

For example, if you write a[ i ] to access the i'th element of a, this is exactly the same as writing *(a+i)

What this means is: "take a (which points to the first element of the array), advance it by i elements, and then get the thing pointed to at that location".
 

Offline sokoloff

  • Super Contributor
  • ***
  • Posts: 1799
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #14 on: July 16, 2018, 07:44:03 pm »
If you use array[index], that works fine to pass a value IN to the function, but not out.

Pointers are the essence of C. Once they click, then you understand C, IMO.

Note that an array variable IS (mostly) a pointer. array[index] is the same as *(array + index).
 
The following users thanked this post: JPortici

Offline ttt

  • Regular Contributor
  • *
  • Posts: 87
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #15 on: July 16, 2018, 07:52:00 pm »
Some good answers here already but saying pointers are not useful vs variables is equivalent to saying that impedance is not useful because it's just resistance. There is a little more to it ;-) In some ways a variable is just a special case of a pointer (or reference). Keep digging and at some point it'll click.
 

Offline bsudbrink

  • Frequent Contributor
  • **
  • Posts: 406
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #16 on: July 16, 2018, 07:59:01 pm »
Pointers are the essence of C. Once they click, then you understand C, IMO.
I would add that once you get this, you are well on your way to understanding machine language and you can then dispense with all of the "high level language" nonsense and program CPUs at the bare metal like god intended  >:D
 

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #17 on: July 16, 2018, 08:04:12 pm »
Keep digging and at some point it'll click.

I hope so ;)
 

Offline SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17814
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #18 on: July 16, 2018, 08:04:51 pm »
Pointers are the essence of C. Once they click, then you understand C, IMO.
I would add that once you get this, you are well on your way to understanding machine language and you can then dispense with all of the "high level language" nonsense and program CPUs at the bare metal like god intended  >:D

em, no, really, not gonna happen.
 

Offline sokoloff

  • Super Contributor
  • ***
  • Posts: 1799
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #19 on: July 16, 2018, 08:08:43 pm »
C is pretty much portable assembly language already. It’s rare that I have to drop from C to asm to accomplish what I want. (Usually only in ISRs or similar to push registers or something.)
 

Offline bsudbrink

  • Frequent Contributor
  • **
  • Posts: 406
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #20 on: July 16, 2018, 08:19:07 pm »
C is pretty much portable assembly language already. It’s rare that I have to drop from C to asm to accomplish what I want. (Usually only in ISRs or similar to push registers or something.)
Agreed for the most part.  Depends on the CPU and the C compiler/toolchain that is available and how big of a PITA it is to get run code to the target.
 

Offline bsudbrink

  • Frequent Contributor
  • **
  • Posts: 406
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #21 on: July 16, 2018, 08:29:47 pm »
Pointers are the essence of C. Once they click, then you understand C, IMO.
I would add that once you get this, you are well on your way to understanding machine language and you can then dispense with all of the "high level language" nonsense and program CPUs at the bare metal like god intended  >:D

em, no, really, not gonna happen.

If you were properly motivated and I could have a couple of hours of your undivided attention, I bet I could teach you 6502 or Z80 assembler.  Once you get one, you can then get any.
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 7764
  • Country: de
  • A qualified hobbyist ;)
Re: [C] Pointers - what is the point?
« Reply #22 on: July 16, 2018, 08:38:40 pm »
A pointer is typically a link to a blob of memory. The blob of memory could be something like a simple character string or a complex structure with lots of data. If you place data in an array and want to sort the data you have to move the data around by copying the complete data sets. If you use a linked list instead (each data set is linked to the next one by a pointer) you only have to change the pointers when sorting. which is much faster than copying lots of RAM. This is only one example of the benefit of pointers.
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4078
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: [C] Pointers - what is the point?
« Reply #23 on: July 16, 2018, 09:11:16 pm »
but if i am pointing at another variable why not just use the variable?
You are doing that with pointers. Except instead of the immutable name “foo”, you use a incrementable and changeable pointer to foo.

You can change the pointer to foo at runtime, without changing a single line of code.

This is all highly abstract, and I could dive into technical details. But let’s keep it simple.

Say have to write a function to display some text on a screen. You write some software to put “hello world” on the screen.
This works, and you feel great. Then you get asked to put another text on the screen.
You recompile, and it shows the other text.
You get asked again, and again. Eventually you’re sick of it, and you use a pointer for the text to show on the screen.
Now everyone can put in an address of where some text is stored that should be on the screen. You are no longer bothered by people requesting texts.
 

Offline rolycat

  • Super Contributor
  • ***
  • Posts: 1101
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #24 on: July 16, 2018, 09:15:45 pm »
If you wanted to process the elements of your array in a separate function, then you could use code like this (complete program):

Code: [Select]
#include <stdio.h>

void print_array(int *array, int size) {                        // function to print the elements of an array             
    for (int i=0; i<size; ++i) {
        printf("Array element %i: %i\n", i, array[i]);
    }
}

int main() {
    int main_array[] = { 5, 4, 3, 2, 1 };                       // create an array and fill it with values
    int array_size = sizeof(main_array)/sizeof(main_array[0]);  // calculate the number of elements
    print_array(main_array, array_size);                        // call a function to print the values
}



The function print_array() has two arguments, a pointer to an array and the number of elements in the array.

You could also specify the arguments like this; it's the same thing:
Code: [Select]
void print_array(int array[], int size) {

Notice that there is only one copy of the array, the definition of which is local to main(), but by passing a pointer you can access the elements in another function, using a different name for the array.

You could just make main_array[] a global variable and avoid using the arguments, but that's not a good idea in larger programs.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf