开发者

how to define a constant array in c/c++?

开发者 https://www.devze.com 2023-03-24 08:24 出处:网络
How to define constant 1 or 2 dimensional array in C/C++? I deal with embedded platform (Xilinx EDK), so the resources are limited.

How to define constant 1 or 2 dimensional array in C/C++? I deal with embedded platform (Xilinx EDK), so the resources are limited.

I'd like to write in third-party header file something like

#define MYCONSTANT 5

but for array. Like

#define MYARRAY(index) { 5, 6, 7, 8 }

What is the mo开发者_StackOverflowst common way to do this?


In C++, the most common way to define a constant array should certainly be to, erm, define a constant array:

const int my_array[] = {5, 6, 7, 8};

Do you have any reason to assume that there would be some problem on that embedded platform?


In C++ source file

extern "C" const int array[] = { 1, 2, 3 };

In header file to be included in both C and C++ source file

#ifdef __cplusplus
extern "C" {
#endif
extern const int array[];
#ifdef __cplusplus
}
#endif


In C++

const int array[] = { 1, 2, 3 };

That was easy enough but maybe I'm not understanding your question correctly. The above will not work in C however, please specify what language you are really interested in. There is no such language as C/C++.


It's impossible to define array constant using the define directive.


I have had a similar problem. In my case, I needed an array of constants in order to use as size of other static arrays. When I tried to use the

const int my_const_array[size] = {1, 2, 3, ... };

and then declare:

int my_static_array[my_const_array[0]];

I get an error from my compiler:

array bound is not an integer constant

So, finally I did the following (Maybe there are more elegant ways to do that):

#define element(n,d) ==(n) ? d :
#define my_const_array(i) (i) element(0,1) (i) element(1,2) (i) element(2,5) 0


#include <string>
#include <iostream>
#define defStrs new string[4] { "str1","str2","str3","str4" }
using namespace std;
...

const string * strs = defStrs;
string ezpzStr = strs[0] + "test" + strs[1];

cout << ezpzStr << endl;

Took me a while to figure this out, but apparently it works like this in C++. Works on my computer anyway.


Only try to understand what the compiler does. When it finds the HASHTAG , it replaces its content into the place where it's writed. So for example, if u do this:

#define MYARRAY { 5, 6, 7, 8 }

byte list[] = MYARRAY ;

You will get it in the array 'list' . Another way to get the same result is:

#define MYARRAY 5, 6, 7, 8

byte list[] = {MYARRAY} ;

In conclusion, the compliler what does is 'cutting' the hashtag and 'pasting' the content of it. I hope I had solved your doubt

0

精彩评论

暂无评论...
验证码 换一张
取 消