passing char Array back from function with pointer

Dear All,
I run into trouble by passing a char array from a function back to where it was called with a pointer. It seems to me like a bug. I try to explain the behavior:

This is my first sketch:

char ArrayMain[7];
char * ptArrayMain;


char* test()
{
 char array[] = "HELLO\0";
 return array;
}

void setup()
{
 Serial.begin(9600);
 Serial.println("Start:");
 
 ptArrayMain = test();
 Serial.print(ptArrayMain);

}

void loop()
{


}

This gives me this result on Serial Monitor:

Port closed
Uploading to I/O board
Opening port
Port open
Start:
AVR I

In front of "AVR I" there are two unknown chars printed. I would not expect this result.

By printing the value of array inside the function test() it gives me the expected result:
Code:

char ArrayMain[7];
char * ptArrayMain;


char* test()
{
 char array[] = "HELLO\0";
 Serial.println(array);
 
 return array;
}

void setup()
{
 Serial.begin(9600);
 Serial.println("Start:");
 
 ptArrayMain = test();
 Serial.print(ptArrayMain);

}

void loop()
{


}

Result:

Port closed
Uploading to I/O board
Opening port
Port open
Start:
HALLO
HALLO

This is a very strange behavior for me. It looks like a bug or? Could anybody explan this to me? Would there a workarround?

I want to prevent using Serial.print just to be able to pass back with char pointer.

Thank you very much!

Your array variable in the test function goes out-of-scope and the data is no longer guaranteed (can be overwritten).

You can make array static or global.

Note:
You don't need to add the terminating '\0' after "HELLO"; it's there because you use a c-string.

Hi sterretje,
thank you very much for your reply.

ohhh, I think the penny droped :wink:

This means actually it makes no sense to pass an arry or pointer after function call. I don't want to have stored the array inside test() permanently.

I just remembered some other example where the array to work on is passed by pointer like following example. Can you please have a look in this if this is the correct way of doing it?

char ArrayMain[7];
char * ptArrayMain = &ArrayMain[0];

test(char* buffer, int sizeofbuffer)
{
 char array[] = "HALLO\0";
 
 strncpy(buffer, &array[0], sizeofbuffer);
 //Serial.println(array);
}

void setup()
{
 Serial.begin(9600);
 Serial.println("Start:");
 //Serial.println((long) &ptArrayMain, DEC);
 
 test(ptArrayMain, sizeof(ArrayMain)/sizeof(ArrayMain[0]));
 
 Serial.print(ptArrayMain);


}

void loop()
{


}

&ArrayMain[0] is the same as ArrayMain :wink:

Further I think it should work; just try it :slight_smile:

Yes, looks good!

Thank you very much!

Seems like I learned a lot for today :wink:

What is the point of the ptArrayMain variable? What is it contributing to your sketch? Something like that looks completely unnecessary. Array types are already trivially convertable into pointers, you don't need to make a separate pointer variable to work with them.