salam
salam

Reputation: 37

updating a value in main after updating it in a function , without pointers

im trying to update values in main according to what changes were made in a function without using pointers

im working on a snake game and to make a move i send the row and column of both the head and the tail to a void function , and inside of it i change them according to what move was made , but they are not updated in main and therefor the next move wont be donr correctly , how can i update them in main but without using pointers ?(its a homework , they specified not using pointers) the code below is for one case which is when the player wants to move down (2 is foe down) and at the end i changed the column of the tail and the row of the head, but it dosent update them in main for when i send the next move

if(move==2){
   if (board[head_row+1][head_cal] != 0) 
            {print_finsih_msg(player,ILLEGAL_MOVE);exit(0);}
   if(head_row == tail_row && head_cal < tail_cal) {               
            board[head_row+1][head_cal] = SHTRODEL_HEAD ; 
            board[head_row][head_cal] = '+' ;
            board[tail_row][tail_cal] = 0;
            tail_cal--;
            head_row++;}

so for examble if the next move is 6 - right it will print that the move is illegal because it still has that the head has its body on the right

Upvotes: 3

Views: 131

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

C offers three general ways of communicating values back to the calling function:

  1. Returning a value - This is the most common way of providing data back for primitive types. However, you are allowed to make a struct type, and return it to the caller.
  2. Passing a pointer - This is common for situations when multiple variables need to be modified.
  3. Using variables visible to both the caller function and the function being called - these could be static or global variables.

Note that it is not enough to keep a position for the head and the tail of the snake: you need to store all positions occupied by your snake in order to be able to advance its tail to the next step. This could be easily implemented with a Circular Buffer sized at the maximum length of the snake:

static int snake_row[MAX_LENGTH+1];
static int snake_col[MAX_LENGTH+1];
static int snake_head = 0;
static int snake_tail = 0;

Arrays snake_row and snake_col between indexes snake_head and snake_tail represent positions currently occupied by the snake. This makes board[][] optional, because you can check for self-crossing by iterating the buffer.

Upvotes: 1

Related Questions