Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing pointers with unions, arrays and functions
    text
    copied!<p>I was never able to fully understand what is going on in the background of passing pointers in functions and how you use them. Right now Im coding a microprocessor in c. The main goal is to create a snake type game that uses an accelormeter. Needless to say my code is filled with errors dealing with pointer implantation.</p> <p>Let me try to break it down. First I have an union </p> <pre><code> typedef union { UINT8 byte; struct { UINT8 x : 4; UINT8 y : 4; }; } snake; </code></pre> <p>The union stores the x and y location of a node in the snake. I use this method so when I check if the byte exists I can do it using the byte. Anyway I initialize it as an array "snake location[64]" which is in the main function. I also have int's of the length and the head and tail of the snake. However trying to pass the union or anything else is where im having the problem. So far my prototypes for the functions are </p> <pre><code>void randGen(UINT8* x, UINT8* y); void nextMove(snake* body, int* length, int* head, int* tail); BOOL setLocation(snake* body,snake temp, int* length, int* head, int*tail, BOOL* newTerm); void clearLocation(snake* body,snake temp, int* length, int* tail, BOOL* repeat); void reset(int* length, int* index, UINT8* location); UINT8 readDirection(); void gameOver(); </code></pre> <p>Here is a snippit of the nextMove function. I pretty much just have more else if statements with more or less the same code so to keep things simple.</p> <pre><code>void nextMove(snake* body[], int* length, int* head, int* tail){ UINT8 direction; int i; snake temp; temp = *body[*head]; do { direction = readDirection(); } while(direction != 4); if(direction == 0) { //up if(temp.y == 0) gameOver(); temp.y -= 1; for(i = 0; i &lt; *length; i++) { if (body[i]-&gt;byte == temp.byte) gameOver(); } if(temp.byte == locOfApple.byte) { } else { clearLocation(body, *temp, length, tail, FALSE); setLocation(body, *temp, length,head,tail, FALSE); *body[*tail] = temp; head = tail; if(++tail &gt;= length) tail = 0; } } </code></pre> <p>Mostly I just need to know how to set the prototype up, how to use the pointer as a value in the function, and what to pass the function. If passing an array (which I believe is different than passing an int) is different, if someone can explain a good way of thinking about it that would really help me grasp this concept. </p> <p>Any help would be appreciated :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload