Snake in C - Integer gets changed without being changed - what's the problem?











up vote
-3
down vote

favorite












(program language is c - when correcting please only use stuff noobs can do, I am just learning this since 1 week)



The problem is: See the "int snakelen = 1;" at the start of main?



I never change that integer. But when I end the game it is 0. Why?



And if i TRY TO CHANGE snakelen mid-game, the game completely breaks and i get windows-error sounds.
What's the matter?



(And the food doesnt spawn randomly although i use a randomizer. And it either spawns bottom-only or top-only - changing about every 5 minutes. another wierd glitch.)



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <time.h>
#include <math.h>

#define SIZE 2048 //32(*2 because every 2nd one is a space) * 32
#define HSIZE 1024 //32 * 32
#define UP_ 1
#define DOWN_ 3
#define LEFT_ 4
#define RIGHT_ 2
#define YSIZE 64 //length of a row (including spaces)

//TO PLAY: Start the game once, right-click the command-promt at the top, click Settings -> Layout . Then change the window size to 64 (hor) * 33 (vert)

int counter = 0;
int gamespeed = 400;//Intervall in which a game-frame gets rendered

int spawnfood(int* freetable, int snakelen)
{
srand ( time(NULL) ); //randomize
int randomIndex = rand()%(HSIZE - 1); //take random non-x-filled position from array
int randomValue = freetable[randomIndex]; //output the random position
return randomValue;
}

int main()
{
int nofood = 1; //is there food in the game? 1 = no
//int tmp = 0; //temporary memory for later
int tmp2 = 0; //temporary memory2
int snakelen = 1; //length of snake
int snakedir = RIGHT_; //Position the snake is looking
int snakeheadxpos = 0; //x-position of snake
int snakeheadypos = 0; //y-position of snake
char q;//The button that was pressed last


char gametable[SIZE]; //the game-screen //fill it with spaces
for(int i = 0; i < SIZE; i++)
{
gametable[i]=' ';
}
gametable[SIZE] = '';


int freetable[(HSIZE)]; // 32*32 list of all pixels, which shows whether a pixel is an x or not
for(int i = 0; i < (HSIZE); i++)
{
freetable[i]= i*2; //fill the array with its numbers
}


//START OF GAME
printf("Press any Button to start the game!n");
getch();
for(int i = 0; i < 31; i++){
printf("n");
}

while(q != 27)
{
counter++;
if(kbhit()) //if button is pressed
{
q = getch(); //q = that button
switch(q) //change the way the snake looks via WASD
{
case 'w':
if(snakedir != DOWN_)
snakedir = UP_;
break;
case 'a':
if(snakedir != RIGHT_)
snakedir = LEFT_;
break;
case 's':
if(snakedir != UP_)
snakedir = DOWN_;
break;
case 'd':
if(snakedir != LEFT_)
snakedir = RIGHT_;
break;
default:
break;
}

}
if(counter%gamespeed == 0) //Renders a game-frame at the intervall of gamespeed
{
switch(snakedir)
{

case UP_:
if(snakeheadypos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadypos--;
break;

case DOWN_:
if(snakeheadypos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadypos++;
break;

case RIGHT_:
if(snakeheadxpos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos++;
break;

case LEFT_:
if(snakeheadxpos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos--;
break;
default:
break;
}

if((gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] == 'o'))
{
//snakelen++; //<-- WHEN YOU REMOVE THE FIRST //, THE GAME STARTS TO BUG AND I GET WINDOWS ERROR SOUNDS!
nofood = 1; //no more food is in the game
}
gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x'; //set the pixel ur at the the moment to 'x'

gametable[tmp2] =' ';
tmp2 = snakeheadypos*64+snakeheadxpos*2;
//spawn food if there is none
if(nofood)
{
gametable[spawnfood(freetable, snakelen)] = 'o';
nofood = 0; //food is already placed
}
printf("%s", gametable); // print the gametable
}
}
exit_loop: ; //if you ran into a wall
printf("Game Over - Score: %d", snakelen);
}









share|improve this question




















  • 2




    I would avoid using goto as it makes code more difficult to follow. Don't get into the habit of using it.
    – Fiddling Bits
    Nov 21 at 14:54








  • 2




    goto is the black sheep of programming. Do not use it!
    – gsamaras
    Nov 21 at 14:56










  • @gsamaras in C goto is sometimes the most appropriate solution.
    – SergeyA
    Nov 21 at 14:56








  • 2




    @SergeyA If goto is the most appropriate solution I'd say you need to refactor/re-architect/modularize your code.
    – Fiddling Bits
    Nov 21 at 14:57








  • 4




    gametable[SIZE] = ''; Here is some undefined behavior. Valid array indices run from 0 to SIZE-1
    – Tim Randall
    Nov 21 at 14:57















up vote
-3
down vote

favorite












(program language is c - when correcting please only use stuff noobs can do, I am just learning this since 1 week)



The problem is: See the "int snakelen = 1;" at the start of main?



I never change that integer. But when I end the game it is 0. Why?



And if i TRY TO CHANGE snakelen mid-game, the game completely breaks and i get windows-error sounds.
What's the matter?



(And the food doesnt spawn randomly although i use a randomizer. And it either spawns bottom-only or top-only - changing about every 5 minutes. another wierd glitch.)



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <time.h>
#include <math.h>

#define SIZE 2048 //32(*2 because every 2nd one is a space) * 32
#define HSIZE 1024 //32 * 32
#define UP_ 1
#define DOWN_ 3
#define LEFT_ 4
#define RIGHT_ 2
#define YSIZE 64 //length of a row (including spaces)

//TO PLAY: Start the game once, right-click the command-promt at the top, click Settings -> Layout . Then change the window size to 64 (hor) * 33 (vert)

int counter = 0;
int gamespeed = 400;//Intervall in which a game-frame gets rendered

int spawnfood(int* freetable, int snakelen)
{
srand ( time(NULL) ); //randomize
int randomIndex = rand()%(HSIZE - 1); //take random non-x-filled position from array
int randomValue = freetable[randomIndex]; //output the random position
return randomValue;
}

int main()
{
int nofood = 1; //is there food in the game? 1 = no
//int tmp = 0; //temporary memory for later
int tmp2 = 0; //temporary memory2
int snakelen = 1; //length of snake
int snakedir = RIGHT_; //Position the snake is looking
int snakeheadxpos = 0; //x-position of snake
int snakeheadypos = 0; //y-position of snake
char q;//The button that was pressed last


char gametable[SIZE]; //the game-screen //fill it with spaces
for(int i = 0; i < SIZE; i++)
{
gametable[i]=' ';
}
gametable[SIZE] = '';


int freetable[(HSIZE)]; // 32*32 list of all pixels, which shows whether a pixel is an x or not
for(int i = 0; i < (HSIZE); i++)
{
freetable[i]= i*2; //fill the array with its numbers
}


//START OF GAME
printf("Press any Button to start the game!n");
getch();
for(int i = 0; i < 31; i++){
printf("n");
}

while(q != 27)
{
counter++;
if(kbhit()) //if button is pressed
{
q = getch(); //q = that button
switch(q) //change the way the snake looks via WASD
{
case 'w':
if(snakedir != DOWN_)
snakedir = UP_;
break;
case 'a':
if(snakedir != RIGHT_)
snakedir = LEFT_;
break;
case 's':
if(snakedir != UP_)
snakedir = DOWN_;
break;
case 'd':
if(snakedir != LEFT_)
snakedir = RIGHT_;
break;
default:
break;
}

}
if(counter%gamespeed == 0) //Renders a game-frame at the intervall of gamespeed
{
switch(snakedir)
{

case UP_:
if(snakeheadypos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadypos--;
break;

case DOWN_:
if(snakeheadypos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadypos++;
break;

case RIGHT_:
if(snakeheadxpos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos++;
break;

case LEFT_:
if(snakeheadxpos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos--;
break;
default:
break;
}

if((gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] == 'o'))
{
//snakelen++; //<-- WHEN YOU REMOVE THE FIRST //, THE GAME STARTS TO BUG AND I GET WINDOWS ERROR SOUNDS!
nofood = 1; //no more food is in the game
}
gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x'; //set the pixel ur at the the moment to 'x'

gametable[tmp2] =' ';
tmp2 = snakeheadypos*64+snakeheadxpos*2;
//spawn food if there is none
if(nofood)
{
gametable[spawnfood(freetable, snakelen)] = 'o';
nofood = 0; //food is already placed
}
printf("%s", gametable); // print the gametable
}
}
exit_loop: ; //if you ran into a wall
printf("Game Over - Score: %d", snakelen);
}









share|improve this question




















  • 2




    I would avoid using goto as it makes code more difficult to follow. Don't get into the habit of using it.
    – Fiddling Bits
    Nov 21 at 14:54








  • 2




    goto is the black sheep of programming. Do not use it!
    – gsamaras
    Nov 21 at 14:56










  • @gsamaras in C goto is sometimes the most appropriate solution.
    – SergeyA
    Nov 21 at 14:56








  • 2




    @SergeyA If goto is the most appropriate solution I'd say you need to refactor/re-architect/modularize your code.
    – Fiddling Bits
    Nov 21 at 14:57








  • 4




    gametable[SIZE] = ''; Here is some undefined behavior. Valid array indices run from 0 to SIZE-1
    – Tim Randall
    Nov 21 at 14:57













up vote
-3
down vote

favorite









up vote
-3
down vote

favorite











(program language is c - when correcting please only use stuff noobs can do, I am just learning this since 1 week)



The problem is: See the "int snakelen = 1;" at the start of main?



I never change that integer. But when I end the game it is 0. Why?



And if i TRY TO CHANGE snakelen mid-game, the game completely breaks and i get windows-error sounds.
What's the matter?



(And the food doesnt spawn randomly although i use a randomizer. And it either spawns bottom-only or top-only - changing about every 5 minutes. another wierd glitch.)



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <time.h>
#include <math.h>

#define SIZE 2048 //32(*2 because every 2nd one is a space) * 32
#define HSIZE 1024 //32 * 32
#define UP_ 1
#define DOWN_ 3
#define LEFT_ 4
#define RIGHT_ 2
#define YSIZE 64 //length of a row (including spaces)

//TO PLAY: Start the game once, right-click the command-promt at the top, click Settings -> Layout . Then change the window size to 64 (hor) * 33 (vert)

int counter = 0;
int gamespeed = 400;//Intervall in which a game-frame gets rendered

int spawnfood(int* freetable, int snakelen)
{
srand ( time(NULL) ); //randomize
int randomIndex = rand()%(HSIZE - 1); //take random non-x-filled position from array
int randomValue = freetable[randomIndex]; //output the random position
return randomValue;
}

int main()
{
int nofood = 1; //is there food in the game? 1 = no
//int tmp = 0; //temporary memory for later
int tmp2 = 0; //temporary memory2
int snakelen = 1; //length of snake
int snakedir = RIGHT_; //Position the snake is looking
int snakeheadxpos = 0; //x-position of snake
int snakeheadypos = 0; //y-position of snake
char q;//The button that was pressed last


char gametable[SIZE]; //the game-screen //fill it with spaces
for(int i = 0; i < SIZE; i++)
{
gametable[i]=' ';
}
gametable[SIZE] = '';


int freetable[(HSIZE)]; // 32*32 list of all pixels, which shows whether a pixel is an x or not
for(int i = 0; i < (HSIZE); i++)
{
freetable[i]= i*2; //fill the array with its numbers
}


//START OF GAME
printf("Press any Button to start the game!n");
getch();
for(int i = 0; i < 31; i++){
printf("n");
}

while(q != 27)
{
counter++;
if(kbhit()) //if button is pressed
{
q = getch(); //q = that button
switch(q) //change the way the snake looks via WASD
{
case 'w':
if(snakedir != DOWN_)
snakedir = UP_;
break;
case 'a':
if(snakedir != RIGHT_)
snakedir = LEFT_;
break;
case 's':
if(snakedir != UP_)
snakedir = DOWN_;
break;
case 'd':
if(snakedir != LEFT_)
snakedir = RIGHT_;
break;
default:
break;
}

}
if(counter%gamespeed == 0) //Renders a game-frame at the intervall of gamespeed
{
switch(snakedir)
{

case UP_:
if(snakeheadypos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadypos--;
break;

case DOWN_:
if(snakeheadypos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadypos++;
break;

case RIGHT_:
if(snakeheadxpos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos++;
break;

case LEFT_:
if(snakeheadxpos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos--;
break;
default:
break;
}

if((gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] == 'o'))
{
//snakelen++; //<-- WHEN YOU REMOVE THE FIRST //, THE GAME STARTS TO BUG AND I GET WINDOWS ERROR SOUNDS!
nofood = 1; //no more food is in the game
}
gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x'; //set the pixel ur at the the moment to 'x'

gametable[tmp2] =' ';
tmp2 = snakeheadypos*64+snakeheadxpos*2;
//spawn food if there is none
if(nofood)
{
gametable[spawnfood(freetable, snakelen)] = 'o';
nofood = 0; //food is already placed
}
printf("%s", gametable); // print the gametable
}
}
exit_loop: ; //if you ran into a wall
printf("Game Over - Score: %d", snakelen);
}









share|improve this question















(program language is c - when correcting please only use stuff noobs can do, I am just learning this since 1 week)



The problem is: See the "int snakelen = 1;" at the start of main?



I never change that integer. But when I end the game it is 0. Why?



And if i TRY TO CHANGE snakelen mid-game, the game completely breaks and i get windows-error sounds.
What's the matter?



(And the food doesnt spawn randomly although i use a randomizer. And it either spawns bottom-only or top-only - changing about every 5 minutes. another wierd glitch.)



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <time.h>
#include <math.h>

#define SIZE 2048 //32(*2 because every 2nd one is a space) * 32
#define HSIZE 1024 //32 * 32
#define UP_ 1
#define DOWN_ 3
#define LEFT_ 4
#define RIGHT_ 2
#define YSIZE 64 //length of a row (including spaces)

//TO PLAY: Start the game once, right-click the command-promt at the top, click Settings -> Layout . Then change the window size to 64 (hor) * 33 (vert)

int counter = 0;
int gamespeed = 400;//Intervall in which a game-frame gets rendered

int spawnfood(int* freetable, int snakelen)
{
srand ( time(NULL) ); //randomize
int randomIndex = rand()%(HSIZE - 1); //take random non-x-filled position from array
int randomValue = freetable[randomIndex]; //output the random position
return randomValue;
}

int main()
{
int nofood = 1; //is there food in the game? 1 = no
//int tmp = 0; //temporary memory for later
int tmp2 = 0; //temporary memory2
int snakelen = 1; //length of snake
int snakedir = RIGHT_; //Position the snake is looking
int snakeheadxpos = 0; //x-position of snake
int snakeheadypos = 0; //y-position of snake
char q;//The button that was pressed last


char gametable[SIZE]; //the game-screen //fill it with spaces
for(int i = 0; i < SIZE; i++)
{
gametable[i]=' ';
}
gametable[SIZE] = '';


int freetable[(HSIZE)]; // 32*32 list of all pixels, which shows whether a pixel is an x or not
for(int i = 0; i < (HSIZE); i++)
{
freetable[i]= i*2; //fill the array with its numbers
}


//START OF GAME
printf("Press any Button to start the game!n");
getch();
for(int i = 0; i < 31; i++){
printf("n");
}

while(q != 27)
{
counter++;
if(kbhit()) //if button is pressed
{
q = getch(); //q = that button
switch(q) //change the way the snake looks via WASD
{
case 'w':
if(snakedir != DOWN_)
snakedir = UP_;
break;
case 'a':
if(snakedir != RIGHT_)
snakedir = LEFT_;
break;
case 's':
if(snakedir != UP_)
snakedir = DOWN_;
break;
case 'd':
if(snakedir != LEFT_)
snakedir = RIGHT_;
break;
default:
break;
}

}
if(counter%gamespeed == 0) //Renders a game-frame at the intervall of gamespeed
{
switch(snakedir)
{

case UP_:
if(snakeheadypos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadypos--;
break;

case DOWN_:
if(snakeheadypos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadypos++;
break;

case RIGHT_:
if(snakeheadxpos==31)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos++;
break;

case LEFT_:
if(snakeheadxpos==0)
{
goto exit_loop; //ran into a wall
}
snakeheadxpos--;
break;
default:
break;
}

if((gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] == 'o'))
{
//snakelen++; //<-- WHEN YOU REMOVE THE FIRST //, THE GAME STARTS TO BUG AND I GET WINDOWS ERROR SOUNDS!
nofood = 1; //no more food is in the game
}
gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x'; //set the pixel ur at the the moment to 'x'

gametable[tmp2] =' ';
tmp2 = snakeheadypos*64+snakeheadxpos*2;
//spawn food if there is none
if(nofood)
{
gametable[spawnfood(freetable, snakelen)] = 'o';
nofood = 0; //food is already placed
}
printf("%s", gametable); // print the gametable
}
}
exit_loop: ; //if you ran into a wall
printf("Game Over - Score: %d", snakelen);
}






c arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 14:53









NathanOliver

84k15113174




84k15113174










asked Nov 21 at 14:52









FireFuro99

32




32








  • 2




    I would avoid using goto as it makes code more difficult to follow. Don't get into the habit of using it.
    – Fiddling Bits
    Nov 21 at 14:54








  • 2




    goto is the black sheep of programming. Do not use it!
    – gsamaras
    Nov 21 at 14:56










  • @gsamaras in C goto is sometimes the most appropriate solution.
    – SergeyA
    Nov 21 at 14:56








  • 2




    @SergeyA If goto is the most appropriate solution I'd say you need to refactor/re-architect/modularize your code.
    – Fiddling Bits
    Nov 21 at 14:57








  • 4




    gametable[SIZE] = ''; Here is some undefined behavior. Valid array indices run from 0 to SIZE-1
    – Tim Randall
    Nov 21 at 14:57














  • 2




    I would avoid using goto as it makes code more difficult to follow. Don't get into the habit of using it.
    – Fiddling Bits
    Nov 21 at 14:54








  • 2




    goto is the black sheep of programming. Do not use it!
    – gsamaras
    Nov 21 at 14:56










  • @gsamaras in C goto is sometimes the most appropriate solution.
    – SergeyA
    Nov 21 at 14:56








  • 2




    @SergeyA If goto is the most appropriate solution I'd say you need to refactor/re-architect/modularize your code.
    – Fiddling Bits
    Nov 21 at 14:57








  • 4




    gametable[SIZE] = ''; Here is some undefined behavior. Valid array indices run from 0 to SIZE-1
    – Tim Randall
    Nov 21 at 14:57








2




2




I would avoid using goto as it makes code more difficult to follow. Don't get into the habit of using it.
– Fiddling Bits
Nov 21 at 14:54






I would avoid using goto as it makes code more difficult to follow. Don't get into the habit of using it.
– Fiddling Bits
Nov 21 at 14:54






2




2




goto is the black sheep of programming. Do not use it!
– gsamaras
Nov 21 at 14:56




goto is the black sheep of programming. Do not use it!
– gsamaras
Nov 21 at 14:56












@gsamaras in C goto is sometimes the most appropriate solution.
– SergeyA
Nov 21 at 14:56






@gsamaras in C goto is sometimes the most appropriate solution.
– SergeyA
Nov 21 at 14:56






2




2




@SergeyA If goto is the most appropriate solution I'd say you need to refactor/re-architect/modularize your code.
– Fiddling Bits
Nov 21 at 14:57






@SergeyA If goto is the most appropriate solution I'd say you need to refactor/re-architect/modularize your code.
– Fiddling Bits
Nov 21 at 14:57






4




4




gametable[SIZE] = ''; Here is some undefined behavior. Valid array indices run from 0 to SIZE-1
– Tim Randall
Nov 21 at 14:57




gametable[SIZE] = ''; Here is some undefined behavior. Valid array indices run from 0 to SIZE-1
– Tim Randall
Nov 21 at 14:57












2 Answers
2






active

oldest

votes

















up vote
4
down vote



accepted










 char gametable[SIZE]; //the game-screen //fill it with spaces
...
gametable[SIZE] = '';


This is wrong. You can index an array of size N with indices 0 through N-1. gametable[SIZE] is outside the array, and assigning to it invokes undefined behavior.






share|improve this answer























  • Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
    – FireFuro99
    Nov 21 at 15:17












  • @FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
    – Tim Randall
    Nov 21 at 15:20










  • I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
    – FireFuro99
    Nov 21 at 15:20






  • 1




    "In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
    – Jabberwocky
    Nov 21 at 15:33






  • 1




    You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
    – William Pursell
    Nov 21 at 15:41


















up vote
0
down vote













Caveat: This isn't a "give a man a fish" answer. It's a "teach a man to fish' answer.



On every one of your statements that reads or writes to an array, you should check the array index for validity.



For example, instead of



gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x';

gametable[tmp2] =' ';


...write...



int index;

index=snakeheadypos*YSIZE + 2*snakeheadxpos;
if(index<0 || index >=SIZE){printf("Index error A: value is %d", index);exit(1);}
gametable[index] = 'x';

index=tmp2;
if(index<0 || index >=SIZE){printf("Index error B: value is %d", index);exit(1);}
gametable[index] =' ';


This sort of technique can help you detect array index problems, which can be a very common source of bugs, and can produce all sort of weird symptoms.






share|improve this answer



















  • 1




    It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
    – Purple Ice
    Nov 21 at 15:50








  • 1




    @PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
    – Tim Randall
    Nov 21 at 15:53










  • Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
    – FireFuro99
    Nov 21 at 16:22











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414703%2fsnake-in-c-integer-gets-changed-without-being-changed-whats-the-problem%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
4
down vote



accepted










 char gametable[SIZE]; //the game-screen //fill it with spaces
...
gametable[SIZE] = '';


This is wrong. You can index an array of size N with indices 0 through N-1. gametable[SIZE] is outside the array, and assigning to it invokes undefined behavior.






share|improve this answer























  • Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
    – FireFuro99
    Nov 21 at 15:17












  • @FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
    – Tim Randall
    Nov 21 at 15:20










  • I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
    – FireFuro99
    Nov 21 at 15:20






  • 1




    "In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
    – Jabberwocky
    Nov 21 at 15:33






  • 1




    You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
    – William Pursell
    Nov 21 at 15:41















up vote
4
down vote



accepted










 char gametable[SIZE]; //the game-screen //fill it with spaces
...
gametable[SIZE] = '';


This is wrong. You can index an array of size N with indices 0 through N-1. gametable[SIZE] is outside the array, and assigning to it invokes undefined behavior.






share|improve this answer























  • Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
    – FireFuro99
    Nov 21 at 15:17












  • @FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
    – Tim Randall
    Nov 21 at 15:20










  • I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
    – FireFuro99
    Nov 21 at 15:20






  • 1




    "In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
    – Jabberwocky
    Nov 21 at 15:33






  • 1




    You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
    – William Pursell
    Nov 21 at 15:41













up vote
4
down vote



accepted







up vote
4
down vote



accepted






 char gametable[SIZE]; //the game-screen //fill it with spaces
...
gametable[SIZE] = '';


This is wrong. You can index an array of size N with indices 0 through N-1. gametable[SIZE] is outside the array, and assigning to it invokes undefined behavior.






share|improve this answer














 char gametable[SIZE]; //the game-screen //fill it with spaces
...
gametable[SIZE] = '';


This is wrong. You can index an array of size N with indices 0 through N-1. gametable[SIZE] is outside the array, and assigning to it invokes undefined behavior.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 at 15:01

























answered Nov 21 at 14:58









William Pursell

128k32205235




128k32205235












  • Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
    – FireFuro99
    Nov 21 at 15:17












  • @FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
    – Tim Randall
    Nov 21 at 15:20










  • I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
    – FireFuro99
    Nov 21 at 15:20






  • 1




    "In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
    – Jabberwocky
    Nov 21 at 15:33






  • 1




    You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
    – William Pursell
    Nov 21 at 15:41


















  • Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
    – FireFuro99
    Nov 21 at 15:17












  • @FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
    – Tim Randall
    Nov 21 at 15:20










  • I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
    – FireFuro99
    Nov 21 at 15:20






  • 1




    "In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
    – Jabberwocky
    Nov 21 at 15:33






  • 1




    You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
    – William Pursell
    Nov 21 at 15:41
















Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
– FireFuro99
Nov 21 at 15:17






Oh :/ In university we were told an array ends in a null-pointer.And as far as i know is a null-pointer. I just use it to make sure the array ends properly. If i remove that line the code doesn't work.
– FireFuro99
Nov 21 at 15:17














@FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
– Tim Randall
Nov 21 at 15:20




@FireFuro99 to be fair, though, if you leave the line in, the code doesn't work.
– Tim Randall
Nov 21 at 15:20












I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
– FireFuro99
Nov 21 at 15:20




I changed it to " = NULL". Doesn't change anything tho. snakelen is still 0 at the end. Help.
– FireFuro99
Nov 21 at 15:20




1




1




"In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
– Jabberwocky
Nov 21 at 15:33




"In university we were told an array ends in a null-pointer." : either you misunderstood something, or it may be time forr your teacher to retire. I suppose rather you've misunderstood something and you're mixing up NUL (nor NULL) terminated strings and and arrays.
– Jabberwocky
Nov 21 at 15:33




1




1




You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
– William Pursell
Nov 21 at 15:41




You were probably not told that an array ends in a null pointer. A string is an array of character with a terminal null value. The array[4] = {'a', 'b', 'c', '} initializes an array of size 4 which is a string of length 3. array[3] is the nul character. Attempting to reference array[4] is an error.
– William Pursell
Nov 21 at 15:41












up vote
0
down vote













Caveat: This isn't a "give a man a fish" answer. It's a "teach a man to fish' answer.



On every one of your statements that reads or writes to an array, you should check the array index for validity.



For example, instead of



gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x';

gametable[tmp2] =' ';


...write...



int index;

index=snakeheadypos*YSIZE + 2*snakeheadxpos;
if(index<0 || index >=SIZE){printf("Index error A: value is %d", index);exit(1);}
gametable[index] = 'x';

index=tmp2;
if(index<0 || index >=SIZE){printf("Index error B: value is %d", index);exit(1);}
gametable[index] =' ';


This sort of technique can help you detect array index problems, which can be a very common source of bugs, and can produce all sort of weird symptoms.






share|improve this answer



















  • 1




    It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
    – Purple Ice
    Nov 21 at 15:50








  • 1




    @PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
    – Tim Randall
    Nov 21 at 15:53










  • Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
    – FireFuro99
    Nov 21 at 16:22















up vote
0
down vote













Caveat: This isn't a "give a man a fish" answer. It's a "teach a man to fish' answer.



On every one of your statements that reads or writes to an array, you should check the array index for validity.



For example, instead of



gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x';

gametable[tmp2] =' ';


...write...



int index;

index=snakeheadypos*YSIZE + 2*snakeheadxpos;
if(index<0 || index >=SIZE){printf("Index error A: value is %d", index);exit(1);}
gametable[index] = 'x';

index=tmp2;
if(index<0 || index >=SIZE){printf("Index error B: value is %d", index);exit(1);}
gametable[index] =' ';


This sort of technique can help you detect array index problems, which can be a very common source of bugs, and can produce all sort of weird symptoms.






share|improve this answer



















  • 1




    It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
    – Purple Ice
    Nov 21 at 15:50








  • 1




    @PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
    – Tim Randall
    Nov 21 at 15:53










  • Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
    – FireFuro99
    Nov 21 at 16:22













up vote
0
down vote










up vote
0
down vote









Caveat: This isn't a "give a man a fish" answer. It's a "teach a man to fish' answer.



On every one of your statements that reads or writes to an array, you should check the array index for validity.



For example, instead of



gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x';

gametable[tmp2] =' ';


...write...



int index;

index=snakeheadypos*YSIZE + 2*snakeheadxpos;
if(index<0 || index >=SIZE){printf("Index error A: value is %d", index);exit(1);}
gametable[index] = 'x';

index=tmp2;
if(index<0 || index >=SIZE){printf("Index error B: value is %d", index);exit(1);}
gametable[index] =' ';


This sort of technique can help you detect array index problems, which can be a very common source of bugs, and can produce all sort of weird symptoms.






share|improve this answer














Caveat: This isn't a "give a man a fish" answer. It's a "teach a man to fish' answer.



On every one of your statements that reads or writes to an array, you should check the array index for validity.



For example, instead of



gametable[snakeheadypos*YSIZE + 2*snakeheadxpos] = 'x';

gametable[tmp2] =' ';


...write...



int index;

index=snakeheadypos*YSIZE + 2*snakeheadxpos;
if(index<0 || index >=SIZE){printf("Index error A: value is %d", index);exit(1);}
gametable[index] = 'x';

index=tmp2;
if(index<0 || index >=SIZE){printf("Index error B: value is %d", index);exit(1);}
gametable[index] =' ';


This sort of technique can help you detect array index problems, which can be a very common source of bugs, and can produce all sort of weird symptoms.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 at 15:26

























answered Nov 21 at 15:16









Tim Randall

1,8531118




1,8531118








  • 1




    It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
    – Purple Ice
    Nov 21 at 15:50








  • 1




    @PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
    – Tim Randall
    Nov 21 at 15:53










  • Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
    – FireFuro99
    Nov 21 at 16:22














  • 1




    It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
    – Purple Ice
    Nov 21 at 15:50








  • 1




    @PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
    – Tim Randall
    Nov 21 at 15:53










  • Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
    – FireFuro99
    Nov 21 at 16:22








1




1




It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
– Purple Ice
Nov 21 at 15:50






It would be better to replace this with a macro which expands to nothing on release builds and checks only on debug builds. It's better to just get used to array[SIZE+1] for this anyway, it's almost expected that the +1 will indicate that the array is both a string that will be used for text and that it will be explicitly nul terminated.
– Purple Ice
Nov 21 at 15:50






1




1




@PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
– Tim Randall
Nov 21 at 15:53




@PurpleIce yes, you're right about the macro. I was assuming that these checks would be used as temporary development aids only, and would be removed once the bugs were out of the code.
– Tim Randall
Nov 21 at 15:53












Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
– FireFuro99
Nov 21 at 16:22




Didn't get the macro part, but that array[SIZE+1] is a great idea! now i can set array[SIZE] to ! THANKS! :D
– FireFuro99
Nov 21 at 16:22


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414703%2fsnake-in-c-integer-gets-changed-without-being-changed-whats-the-problem%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Berounka

Sphinx de Gizeh

Different font size/position of beamer's navigation symbols template's content depending on regular/plain...