Reputation: 2361
I'm extremely new to C, so I'm sure this is really easy.
I'm trying to declare an array[10]
of fractions in a header file and define it as a static variable in my example.c
file. I initialize it in my function init_heap(). All elements of the array are null when that function returns, however. How do I do this properly? I need the changes to myArray to stick.
Header snippet:
struct fraction
{
signed char sign;
unsigned int numerator;
unsigned int denominator;
};
extern struct fraction *myArray[10];
example.c:
//includes...
static struct fraction *myArray[10];
void init_heap()
{
struct fraction myArray[] = {
{0,0,1},
{0,0,2},
{0,0,3},
{0,0,4},
{0,0,5},
{0,0,6},
{0,0,7},
{0,0,8},
{0,0,9},
{0,0,10}
};
beginFreeIndex = 0;
}
//etc...
Thanks in advance..
Upvotes: 3
Views: 1030
Reputation: 8049
struct fraction myArray[] = {
{0,0,1},
{0,0,2},
{0,0,3},
{0,0,4},
{0,0,5},
{0,0,6},
{0,0,7},
{0,0,8},
{0,0,9},
{0,0,10}
};
You're making a local array called myArray
which is hiding the global myArray
. Then, when your function ends, the local myArray
goes out of scope and you lose everything. Meanwhile, the global myArray
is still null.
Try:
myArray = {
{0,0,1},
{0,0,2},
{0,0,3},
{0,0,4},
{0,0,5},
{0,0,6},
{0,0,7},
{0,0,8},
{0,0,9},
{0,0,10}
};
EDIT:
As @David Heffernan points out, you're declaring an array of pointers to struct fraction
in this line: extern struct fraction *myArray[10];
. I think you're trying to get just an array of struct fraction
, so you should try this instead in place of that line: extern struct fraction myArray[10]
Upvotes: 2