开发者

struct value cannot be changed ( c language )

开发者_Python百科

I wrote a piece of c code :

struct Res {
    int a;
    float b;
    double c;
};

struct Res ModRes(struct Res rrr)
{
    rrr.a=222;
    return rrr;
}

int main()
{
    struct Res r[10]={1,2,3};
    ModRes(r[0]);
    return 0;
}

why r[0] is not 222 after ModRes ?


In C, arguments are passed by value. You could make the function accept a struct Res * rather than a struct Res:

struct Res *ModRes(struct Res *rrr)
{
    rrr->a=222;
    return rrr;
}

int main()
{
    struct Res r[10]={1,2,3};
    ModRes(&r[0]);
    return 0;
}


The struct is passed by value (copied) to the ModRes function. So the original value is not changed.


You declared ModRes() to be a function that accepts by value a structure of type Res, and then returns a structure of type Res. However, when you called ModRes() from Main(), you passed it a structure of type Res, but did nothing with the result that ModRes() returned. So, r[0].a didn't change. You'd need to change the call to be:

r[0] = ModRes( r[0] );

to make your code work.

However, as the other responding posts have indicated, there is a much better way to accomplish your goal. You need to change ModRes so that it can accept its argument by reference instead of by value; that is, you need to pass ModRes a pointer to the r[0] structure. Your code should be:

void ModRes(struct Res *rrr);   // function prototype

void ModRes(struct Res *rrr)    // function definition
{ 
    rrr->a=222; 
} 

and then, in Main():

ModRes(&r[0]);

The number of program bytes generated using this method will generally be far less than the one that passed the argument by value. This method needs only to pass one argument to ModRes: the structure's address. ModRes then modifies the caller's structure through that address. It returns nothing, because the modification has already been made.

The other method copied all of the structure's contents to temporary storage (usually the stack), and called ModRes, which then modified element a of that copy, changing it to 222. ModRes then returned that copy (or a copy of that copy, depending on your compiler) by copying it to temporary storage (usually the stack), and returning to the caller, which would then copy that structure from the stack back to the caller's r[0] structure.


Because you are modifying the local copy that the function receives as an argument. Research about pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜