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.
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));
}