如何在c/c++中定义一个常量数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6892586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:50:04  来源:igfitidea点击:

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

c++carraysconst

提问by Andrey Pesoshin

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

如何在 C/C++ 中定义常量一维或二维数组?我处理嵌入式平台(Xilinx EDK),所以资源有限。

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 most common way to do this?

最常见的方法是什么?

回答by sbi

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

在 C++ 中,定义常量数组的最常见方法当然应该是定义一个常量数组

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?

您是否有任何理由假设该嵌入式平台会出现问题?

回答by jahhaj

In C++ source file

在 C++ 源文件中

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

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

在要包含在 C 和 C++ 源文件中的头文件中

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

回答by jahhaj

In C++

在 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++.

这很容易,但也许我没有正确理解你的问题。以上在 C 中不起作用,但请指定您真正感兴趣的语言。没有像 C/C++ 这样的语言。

回答by undone

It's impossible to define arrayconstant using the define directive.

array使用define指令定义常量是不可能的。

回答by Ojos

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

回答by Silikiln

#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 mycomputer anyway.

我花了一段时间才弄清楚这一点,但显然它在 C++ 中是这样工作的。无论如何在我的电脑上工作。