Define and array in C++

148 Views Asked by At

I have a question about this error from g++ on linux:

srcs/../incs/file.hpp:21:27: error: taking address of temporary array
 # define KEY_ESC_ (char[]){27, 0, 0, 0, 0, 0, 0}
                       ^~~~~~~~~~~~~~~~~~~~~~
 srcs/main.cpp:91:16: note: in expansion of macro 'KEY_ESC_'

This is in a define as you can see. I don't understand why g++ say taking address of temporary array

It's more global than temporary...

This value is the key escape got from read

Any way ...

How can I solve it?

This code works on osx, but I need gross-compilation on linux ...

Thank you

2

There are 2 best solutions below

0
Bas in het Veld On BEST ANSWER

If you use a define statement, all instances of KEY_ESC_ in your code will be literally replaced by (char[]) {27, 0, 0, 0, 0, 0, 0}, which will at that point in your code become a temporary variable.

0
SHR On

I guess you have function like this: void f(char** A) so you pass &KEY_ESC_

{27, 0, 0, 0, 0, 0, 0} is const char array.

by casting it to char[] you create a temporary variable.

the problem is that the method can save the address of the temporary and reuse it after it been released.

You can try to solve it by use a const:

const char KEY_ESC_[] = {27, 0, 0, 0, 0, 0, 0};

and call to method:

void f2(const char** A)

with:

f2(&KEY_ESC_);