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;
}
CodePudding user response:
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, ¤t_i, ¤t_j))