I have this code in my main file:
int grid[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ,
1 , 2 , 3 , 2 , 3 , 2 , 3 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ,
1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 ,
1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
How do I define it in my header so that I can access the variable throughout my class?
If you must put it in a header file, use extern or static : // option 1 // . h extern char axis[3][8]; // . c char axis[3][8] = { "X", "Y", "Z" }; // option 2 // .
To declare an array in Objective-C, we use the following syntax. type arrayName [ arraySize ]; type defines the data type of the array elements. type can be any valid Objective-C data type.
The header file -- the whole thing: array.h This header file is similar in format to the Rational class examples. The preprocessor statements and the using statement at the beginning of the . h file are similar (except a different identifier, ARRAY_H, to match the filename is used):
extern int grid[];
Let's suppose you had some code like this:
int grid[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ,
1 , 2 , 3 , 2 , 3 , 2 , 3 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ,
1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 ,
1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
int arr_sum(int* arr, int len)
{
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}
int main(int argc, char** argv)
{
printf("%d\n", arr_sum(grid, sizeof(grid)/sizeof(int) ));
return 0;
}
If you wanted to separate this out into two different files, say, you could have the following, for example:
in grid.c:
int grid[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ,
1 , 2 , 3 , 2 , 3 , 2 , 3 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ,
1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 ,
1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
In main.c:
extern grid[];
int arr_sum(int* arr, int len)
{
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}
int main(int argc, char** argv)
{
printf("%d\n", arr_sum(grid, sizeof(grid)/sizeof(int) ));
return 0;
}
You can't define it in your header. You have to declare it in your header and define it in a source (.m
) file:
// In MyClass.h
extern int grid[];
// In MyClass.m
int grid[] = {...};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With