Variable changed in function not seen by caller?

柔情痞子 提交于 2019-11-28 14:12:31
Alex Gidan

You're passing the parameter "by value" and not "by reference". This means that once you pass px to the function you have a copy of it inside the function, so any modification inside the function won't affect the original px.

Callee

Try with this (see we are now passing to the function the parameter as a pointer):

void checkForPoker(int j, int* px) //j is the player's number, px is the player's scoreholder
{
    if ((c1==c2 && c2==c3 && c3==c4) || (c1==c2 && c2==c3 && c3==c5) || (c1==c2 && c2==c4 && c4==c5) || (c1==c3 && c3==c4 && c4==c5))
    {
        printf("\n\nEl Jugador %d tiene un poker de %ss!", j, traducirCarta(c1));
        *px = 8;
    }
    if (c5==c2 && c2==c3 && c3==c4)
    {
        printf("\n\nEl Jugador %d tiene un poker de %ss!", j, traducirCarta(c2));
        *px = 8;
    }
}

Caller

This implies also a change in the calling code. Instead of passing the integer you will have to pass the address to the integer, something like:

Instead of

int a = 2;
checkForPoker(2, a);

You will have to do something like:

int a = 2;
checkForPoker(2, &a);

Alternative Way

As suggested by a SO user (Charlon) you could choose another approach, avoiding the use of pointers: you can use px as return value of the function:

int checkForPoker(int j) //j is the player's number
{
    int px = 0;
    if ((c1==c2 && c2==c3 && c3==c4) || (c1==c2 && c2==c3 && c3==c5) || (c1==c2 && c2==c4 && c4==c5) || (c1==c3 && c3==c4 && c4==c5))
    {
        printf("\n\nEl Jugador %d tiene un poker de %ss!", j, traducirCarta(c1));
        px = 8;
    }
    if (c5==c2 && c2==c3 && c3==c4)
    {
        printf("\n\nEl Jugador %d tiene un poker de %ss!", j, traducirCarta(c2));
        px = 8;
    }
    return px;
}

And then you could assign player's scoreholder like this:

player->scoreholder = checkForPoker(int j) //j is the player's number

Please note that I'd stick to the first approach for performance reasons (superfluous copies in the second approach).

Further Readings

For an extended reading on the subject you could find useful these links: [1] [2]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!