简体   繁体   中英

Modifying struct members through a pointer passed to a function

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? (ie 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 sTest pointer 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 of main() , ID would be 3. The changes done inside changePointer() are done on the same memory as the changes done in main() .

An easy fix would be:

int main(void)
{
   struct test aTest;
   sTest = &aTest;    /* Notice the ampersand! */
   sTest->start = true;
   changePointer(sTest);

   return 0;
}

Also note that C before C99 doesn't have a true keyword.

1) First thing your code will crash since you are not allocating memory for saving structure.. you might need to add

 sText  = malloc(sizeof(struct test));

2) After correcting the crash, you can pass structure pointer and the changes you make in changePointer function will reflect in main and vizeversa..

3) But since you are not printing anything, there wont be any output to your program..

The only question is why do you need a test pointer in a global name space? Second is that you do not have any memory allocation operations. And you have a pointer as an input parameter of your function. Therefore structure where it points to will be changed in "changePointer".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM