Pointer to array element

I think i want to have a pointer to an element of an array..
I have an array with alot of values, and I would like to use a more user friendly variable to point to specific elements in this array.

for instance 'pointerToElement2' points to values[2] (and is thus nothing more than a shortcut/more userfriendly name):

int values[]={0,1,2,3};
int * pointerToElement2 = values[2];

void setup(){
values[2] = 5;

void loop(){
Serial.println("value of element 2:" + String(&pointerToElement2));//should print out .. 5
pointerToElement2=6; //(gives error: invalid conversion from 'int' to 'int*' [-fpermissive])

Serial.println("value of element 2:" + String(&pointerToElement2)); //should print out .. 6
values[2] = 1;
Serial.println("value of element 2:" + String(&pointerToElement2)); //should print out .. 1

All the printouts give an error "no matching function for call to 'String(int**)
spn("value of element 2:" + String(&pointerToElement2))"

How should i write the functioning desired code? :slight_smile:

You've just totally botched the pointer syntax. Looks like the pointer section of a good C++ tutorial might help a lot.

int * pointerToElement2 = values[2];

So if values[2] is 3 do you want pointerToElement2 to point to that 3 or to point to whatever happens to be in memory address 3?

int * pointerToElement2 = values + 2;


int * pointerToElement2 = &values[2];

And you're taking address of, not getting the thing pointed to here:

Serial.println("value of element 2:" + String(&pointerToElement2));

should be

Serial.println("value of element 2:" + String(*pointerToElement2));

you forgot to dereference the pointer. Again, do you want the value of 6 or do you want the pointer to point to memory address 6?


Hmm, I messed up big time! You helped me alot, thanks!
I've got it all working nicely now.
Guess I'll have to retake that pointer section soon.. :slight_smile:

If you don't want to change the position your pointer is pointing to, but just use an alias for an element,
a reference would be simpler.

int dummy[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int& element2 = dummy[2];

void setup() {
  Serial.print(F("it was "));
  element2 = 42;
  Serial.print(F(", it's now "));
  Serial.print(F(", just like it's array element "));
void loop() {}
it was 3, it's now 42, just like it's array element 42

Thanks Whandall, that's a nice alternative! Simple but effective.

The term 'alias' didn't cross my mind. Otherwise I might have found a solution in my searches through google without bothering you guys..

Thank you for your input.

without bothering you guys..

Don't worry about bothering us with serious questions, when you clearly want to learn.

What bothers us is the "Hey, I've put this off until the last moment, and I'm not interested in learning, I just need you to write this sketch for me, and explain how it works so I can explain it" type of posts.