I'm fairly new to C, so please bear with me :) I'm trying to learn the language, and I have found trouble when trying to make changes to elements of the same struct.
Consider the following code:
#include <stdio.h>
struct aStruct{
int someNum;
};//end wordGuessResources struct
int updateSomeNumber(struct aStruct thing){
printf("\nBefore updating someNum is %d.", thing.someNum);
thing.someNum++;
printf("\nAfter updating someNum is %d.", thing.someNum);
return 0;
}
int main(){
struct aStruct thing;
thing.someNum = 2;
updateSomeNumber(thing);
printf("\nIn main, someNum is now %d.", thing.someNum);
updateSomeNumber(thing);
printf("\nIn main, someNum is now %d.", thing.someNum);
return 0;
}//end main
Running this code will produce the output:
Before updating someNum is 2.
After updating someNum is 3.
In main, someNum is now 2.
Before updating someNum is 2.
After updating someNum is 3.
In main, someNum is now 2.
So obviously when I pass thing
to updateSomeNumber
the first time, it is accepting the same copy of thing
because it already knows someNum
is 2 (see first line of output).
But what seems to be occurring is that after it affects that value of thing
, when we return back to the main
function none of the changes seem to have been recorded (because in main
the someNum
is still 2, not 3).
So I theorize that updateSomeNumber
must be taking in a copy of thing
that was initially edited in main, but is not modifying the original instance?
If that is indeed the case, how do I pass the exact instance of thing
that main
uses into a function so that it will affect that instance?