I am having trouble putting together some code in which I wish to have the following:
Have a header file
myHeader.h
in which I create a typestruct myStruct
with membersint number1
,int number2
andint number3
. This file would also contain a "getter" prototype for getting the address of each of the members in astruct
instance.A translation unit (
file.c
) in which I declare a static instance ofstruct myStruct
, i.e.static struct myStruct myStructInstance
. This translation unit defines the "getter" functions (I will illustrate with a code example at the end of the post).Another header file
anotherHeader.h
in which I wish to - now this is a tricky bit that's causing problems for me - get the addresses of each of the members of a static structure and use them for something.
Here's an example to show what I am talking about.
myHeader.h
struct myStruct{
int number1;
int number2;
int number3;
};
int* get_number1(void);
int* get_number2(void);
int* get_number3(void);
file.c
#include <myHeader.h>
static struct myStruct myStructInstance = {
.number1 = 0,
.number2 = 0,
.number3 = 0
};
int* get_number1(void){
struct myStruct* ptr_myStructInstance = &(myStructInstance);
int* number1Address = &(ptr_myStructInstance->number1);
return number1Address;
}
int* get_number2(void){
struct myStruct* ptr_myStructInstance = &(myStructInstance);
int* number2Address = &(ptr_pfcVariables->number2);
return number2Address;
}
int* get_number3(void){
struct myStruct* ptr_myStructInstance = &(myStructInstance);
int* number3Address = &(ptr_myStructInstance->number3);
return number3Address;
}
anotherHeader.h
#include <myHeader.h>
int* pNumber1 = get_number1();
int* pNumber2 = get_number2();
int* pNumber3 = get_number3();
The problem is that the code shown above throws "initializer element is not constant" error in anotherHeader.h
. I've read a few answers as to why we cannot use non-constant expressions when initializing variables with static storage duration, however I do not understand how this relates to my code.