Reputation: 334
I'm trying to pass a 2D char* array, a 1D int array and an integer to a function using a struct, however I am having trouble wrapping my head round how to pass them by reference using pointers, rather than just by value. I need all variables to be editable by the functions they are passed into, and have that value reflected throughout the whole program, not just within the function scope. Essentially like a global variable, but passed from function to function using structs, defined initially in the main
function.
I initially was using global variables during development, as it worked and it was easy, however I ran into some issues accessing the values in one of the arrays (when accessed from a certain function it would return empty), and I know that global variables are generally a bad idea.
I am using GTK, so as far as I'm aware the only way to pass multiple arguments into a callback is to use structs, hence why I need to pass them via a struct, rather than passing them directly into the function. Unless I'm wrong?
I need to define the following:
char* queuedHashes[100][101];
int queuedHashTypes[100] = {(int)NULL};
int hashCount = 0;
I've been having trouble understanding the pointer and struct syntax required to achieve this and the methods I have tried have led to me running into the char* array type being not assignable
, so have not been able to implement anything that works so far.
Any help would be greatly appreciated, thanks.
Upvotes: 0
Views: 126
Reputation: 409196
To pass a structure by "reference" (I put it in quotes because C doesn't have "references") you simply pass a pointer to the structure. The contents of the structure is in the memory pointed to by the structure pointer.
So if you have a structure like
struct myStruct
{
char* queuedHashes[100][101];
int queuedHashTypes[100];
int hashCount;
};
Then you could have a function like
void myFunction(struct myStruct *theStructure)
{
theStructure->queuedHashTypes[0] = 1;
}
And use the structure and the function something like this:
int main(void)
{
struct myStruct aStructure; // Define a structure object
aStructure.queuedHashTypes[0] = 0;
printf("Before calling the function queuedHashTypes[0] is %d\n",
aStructure.queuedHashTypes[0]);
myFunction(&aStructure); // Pass a pointer to the structure
printf("The function initialized queuedHashTypes[0] to %d\n",
aStructure.queuedHashTypes[0]);
}
The program above should print that queuedHashTypes[0]
is 0
before the function call, and 1
after the call.
Upvotes: 1