EDIT:
What the difference between accessing an element in a array pointer via index pointer[i]
vs. via pointer incrementation pointer+1
.
People are marking this question as duplicate to this question
I have a hard time understanding how? Sure, it's a question regarding arrays and pointers, but the question similarities ends there. Sure, the references to C99 might help someone to dig deeper in C99.. but then, why use SO?
END EDIT
I have a struct (say defined so that all C files have access to it)
typedef struct
{
uint8_t a;
uint8_t b;
} task_t;
And in one C file (say Sub.c) I create an array of such structs
task_t ossList[10] = {};
which are further filled with values for a
and b
during runtime
In the same C file (Sub.c) I've written a function which enables other C files to get this struct array.
void HLP_GetStruct(task_t ** ossListGet) {
*ossListGet = ossList;
}
The way I get the struct from other files (say Top.c) is by:
task_t * ossList;
HLP_GetStruct(&ossList);
for (k=0; k<nTasks; k++) {
printf("OssList %d %d", ossList[k].a, ossList[k].b)
}
And it's all good. But then when I looked more closely I wondered how this can even work. what's really going on?
In my outer C file (Top.c), I initialize a pointer to same type of struct.
task_t * ossList;
I then pass the reference to the other C file (Sub.c)
HLP_GetStruct(&ossList);
and in that C file (Sub.c) I point my pointer to the "real" ossList struct array and I somehow get a pointer array back!?
void HLP_GetStruct(task_t ** ossListGet) {
*ossListGet = ossList;
}
And I can access the indices by
for (k=0; k<nTasks; k++) {
printf("OssList %d %d", ossList[k].a, ossList[k].b)
}
How?
(I've never done it like this before, my arrays have more or less always been declared as pointers, and pointer points by default to first element and you can "copy" over the pointer etc...)
Sub.c
task_t ossList[10] = {};
DoSomethingWithStructArray();
void HLP_GetStruct(task_t ** ossListGet) {
*ossListGet = ossList;
}
Top.c
task_t * ossList;
HLP_GetStruct(&ossList);
for (k=0; k<nTasks; k++) {
printf("OssList %d %d", ossList[k].a, ossList[k].b)
}