-3

I am having trouble getting the ROBX and ROBY variables to print in the main function. This is a small portion of my program and I do not know what I am doing wrong. Thanks!

#include <stdio.h>
#include <time.h>
#define ROW 8
#define COLUMN 8

int robot (int m[ROW][COLUMN], int ROBX, int ROBY);
int ROBX;
int ROBY;

int main(void)
{
    printf("%d %d\n", ROBX, ROBY);
    return 0;
}
int robot (int m[ROW][COLUMN], int ROBX, int ROBY)
{   
    // ensure different output each time program is run
    srand ( time(NULL) );    
        // Pick a random spot to place the robot
        int placed = 0;
        int ROBX;
        int ROBY;
        while(placed == 0) 
        {
            int t = rand() % ROW;
            int y = rand() % COLUMN;
            if(m[t][y] == 0) 
            {
                m[t][y] = -2;
                placed = 1;
                ROBX = t;
                ROBY = y;
            }
            return ROBX, ROBY;
        }
}

1 Answers1

2

There are several problems with your code.

For one thing, you never call robot, so none of those modifications to your variables are happening.

For another, you're not allowed to return multiple values from a function: The line return ROBX, ROBY; is NOT doing what you think it's doing.

Finally, your function doesn't make a lot of sense. You intend to pass in ROBX and ROBY as parameters. That won't work the way you think it will, but it's not a terrible idea in general. But when you create local variables also called ROBX and ROBY. As commenters have noted, that will hide both the global variables and the parameters, so you end up only modifying those locally-defined variables.

There are two ways you can fix this:

  1. Don't create local variables and don't pass parameters. Just modify the global variables directly.
  2. Still don't create local variables, and make your function accept two int * parameters. This will allow you to pass in the global variables when you call robot, so you can modify those parameters in a persistent way. See this question for more details.

In either case, you will need to actually call your robot function.

Jason Baker
  • 2,471
  • 3
  • 23
  • 28