Assigning char** ptr within a for loop gives weird result

I have no idea why this is happening, hope somebody can explain.

Here an example:

void setup() {
  Serial.begin(19200);
  
  char text[] = "hello there";
  char** ptr;

  //uncomment this line for weird result
  //for(int i = 0; i < 1; i++)
    *ptr = text;

  Serial.println(*ptr);
  delay(1000); exit(0);
}

void loop() {
  // put your main code here, to run repeatedly:
  
}

If you uncomment the for-loop it prints unknown(weird) charachters instead of “hello there” as I would expect. It works without the loop.

I’ve tested the same scenario with a single pointer (*ptr), no problems there.

Edit: Im running the Code on a NANO using Arduino IDE 1.8.9

When I run your code with or without the 'for' loop commented out, in the serial monitor I get:-hello there(UNO, Arduino software V1.6.9)

On another topic, why are you doing this?:-exit(0) Edit: And on yet another topic, thank you for placing your code inside code tags. Not many first-time posters do that.

Just to confirm, I tested it again, still weird result. I should’ve mentioned I’m running the Code on a NANO (probably a fake one, not sure I don’t own it) Arduino Software 1.8.4.

For now Im using an Array which works fine:

void setup() {
  Serial.begin(19200);

  char text[] = "hello there";
  char* ptr[42];

  //this works
  for(int i = 0; i < 1; i++)
    ptr[i] = text;

  Serial.println(*ptr);
  delay(1000); exit(0);
}

void loop() {
  // put your main code here, to run repeatedly:
   
}

But I’m still curious why I get such random a result with the example from my original post. Hope somebody with a NANO can confirm.

The

exit(0);

is there because I just wanted to test the setup function real quick, no need to let the Board loop all the time while it’s connected (it doesnt’ really matter though, thats true).

You are using an uninitialized pointer. You are writing to some random place in memory.

  char text[] = "hello there";
  char** ptr;
  *ptr = text;  // Set the memory pointed to by 'ptr' to point to 'text'

Using an array of pointers is one solution. Initializing 'ptr' is another solution:

char text[] = "hello there";
  char *ptr1;
  char **ptr = &ptr1;
    *ptr = text;  // Set 'ptr1' (the pointer pointed to by 'ptr') to point to 'text'