英文:
Define a two-dimensional macro array for use in multiple functions
问题
所以例如:
#define char fruits[5][8] = {"APPLES", "ORANGES", "PEARS", "TOMATOES", "CABBAGES"};
function a() { 这个函数使用了fruits数组。 }
function b() { 这是另一个使用fruits数组的函数。 }
function c() { 这是另一个使用fruits数组的函数。 }
现在,它在主函数中,但我希望它在全局范围内访问,并且它是一个常量。
英文:
So for example:
#define char fruits[5][8] = {"APPLES", "ORANGES", "PEARS", "TOMATOES", "CABBAGES"};
function a() { This function uses the fruits array. }
function b() { This is another function that uses the fruits array. }
function c() { This is yet another function that uses the fruits array. }
Right now, it is in the main function but I want it to be accessed globally and it to be a constant.
答案1
得分: 3
你不需要使用宏来完成这个任务。你可以简单地声明一个全局变量。
char fruits[5][8] = {
"APPLES",
"ORANGES",
"PEARS",
"TOMATOES", // 需要9个字符,而不是8个。如果你尝试打印"TOMATOES" ... 你可能会得到垃圾值!
"CABBAGES"
};
但是... 你有一个问题。 "Tomatoes" 和 "Cabbages" 都是八个字符长。要容纳一个八个字符的字符串,你需要九个字符的空间来容纳空字符。
如果你真的想要它们成为常量,那么将其声明为包含五个 const char
指针的数组,而不是包含五个包含八个字符的数组的数组。char
数组可以修改,字符串文字不能。
const char *fruits[5] = {
"APPLES",
"ORANGES",
"PEARS",
"TOMATOES",
"CABBAGES"
};
此外,这些不需要存在于全局级别。你可以声明 a
、b
和 c
以将它们作为参数传递。
void a(const char *strings[], size_t n) {
// ...
}
int main(void) {
const char *fruits[5] = {
"APPLES",
"ORANGES",
"PEARS",
"TOMATOES",
"CABBAGES"
};
a(fruits, sizeof(fruits) / sizeof(*fruits));
}
英文:
You don't need to use a macro to accomplish this. You can simply declare a global variable.
char fruits[5][8] = {
"APPLES",
"ORANGES",
"PEARS",
"TOMATOES", // Need 9 characters, not 8. If you tried to print "TOMATOES" ... you'll probably get garbage!
"CABBAGES"
};
But... you have an issue. "Tomatoes" and "Cabbages" are both eight characters long. To hold an eight character string, you need nine characters of space to accommodate the null terminator.
If you really want them to be constants, then declare it as an array of five const char
pointers rather than an array of five arrays of eight characters. A char
array can be modified. A string literal cannot.
const char *fruits[5] = {
"APPLES",
"ORANGES",
"PEARS",
"TOMATOES",
"CABBAGES"
};
Further, there's no need for these to live at a global level. You can declare a
, b
, and c
to take them as an argument.
void a(const char *strings[], size_t n) {
// ...
}
int main(void) {
const char *fruits[5] = {
"APPLES",
"ORANGES",
"PEARS",
"TOMATOES",
"CABBAGES"
};
a(fruits, sizeof(fruits) / sizeof(*fruits));
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论