for instance this code:
struct test{
int ID;
bool start;
};
struct test * sTest;
void changePointer(struct test * t)
{
t->ID = 3;
t->start = false;
}
int main(void)
{
sTest->ID = 5;
sTest->start = true;
changePointer(sTest);
return 0;
}
If I was to execute this code, then what would the output be? (i.e. if I pass a pointer like this, does it change the reference or is it just a copy?)
Thanks in advance!
Your program doesn’t have any output, so there would be none.
It also never initializes the
sTestpointer to point at some valid memory, so the results are totally undefined. This program invokes undefined behavior, and should/might/could crash when run.IF the pointer had been initialized to point at a valid object of type
struct test, the fields of that structure would have been changed so that at the end ofmain(),IDwould be 3. The changes done insidechangePointer()are done on the same memory as the changes done inmain().An easy fix would be:
Also note that C before C99 doesn’t have a
truekeyword.