简体   繁体   中英

Function pointer not assigning value in C

let me explain my issue i'm working on a simple program where you define a 2D array, in which you have a robot that starts on position (0, 0). then input a number of expressions ( U - Up, D - Down, L - Left, R - Right). if you input either of those, the 'robot' should change its coordinates(incrementing by 1), based on the expression.

right now, i am trying to edit the coordinates of the values in the while() loop, but i tried debugging it and even if i enter a valid expression (for example D, for down), the coordinates aren't modified.

for example, if if i entered DR, my final coordinates should be (1, 1).

code:

#include<stdio.h>
#include<stdlib.h>

int check_pos(char expression, int i, int j) {
    int* pos;
    int returnValue;
    switch (expression)
    {
        case 'U':
            pos = &j;
            *pos++;
            returnValue = 1;
            break;
        
        case 'D':
            pos = &j;
            *pos--;
            returnValue = 1;
            break;

        case 'L':
            pos = &i;
            *pos--;
            returnValue = 1;
            break;

        case 'R':
            pos = &i;
            *pos++;
            returnValue = 1;
            break;

        default:
            returnValue = 0;
            break;
    }
    return returnValue;
}

int main()
{

    int n, m;
    int current_i = 0, current_j = 0;
    

    printf("Input values:\n");
    scanf("%d %d", &n, &m);
    
    char expression;
    scanf(" %c", &expression);
   while(check_pos(expression, current_i, current_j)) {
        check_pos(expression, current_i, current_j);
        scanf("%c", &expression);
        
    } 

    printf("Expression: %c\n", expression);
    printf("Final positions: %d %d\n", current_i, current_j);

    return 0;
}

Thats not how to 'pass by refereence ' in C

You need

int check_pos(char expression, int *i, int *j)
...
    case 'U':
    (*j)++;
    returnValue = 1;
    break;

and call it like this

 while (check_pos(expression, &current_i, &current_j))

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