Help with a random map generator.

+1 Ben Norris · January 9, 2015
I'm creating a simple text based fighting game with a friend, and I'm in charge of the random map generator. The idea, is the player can innput map dimensions, and the code generates one boss room, x number of shops and the rest are normal rooms. I have a program that works for 3x3 and 2x2, but if the player inputs 4 (at the moment I'm focusing on only using square maps despite the variables for rectangular maps being there) the program crashes.
My current code is here: http://pastebin.com/fyH8SwH9
Could someone please explain why it crashes with 4 or more? I'm completely stuck!

Post a Reply

Replies

Oldest  Newest  Rating
0 c student · January 9, 2015
int main()
{
 
    int mapArray[mapDim*mapDim];    // you've declared your array here
    int i;
 
    srand(time(NULL));
 
    printf("Enter your desired map size:\n");//Only works for 3 or 2 for some reason
    scanf(" %d", &mapDim);    // you've inputted the size for mapDim here
 
   // problem from this point onwards is... your mapArray is still of size whatever where
   // you have previously declared it...

    bossRoomGen();
 
    for(i = 0; i<(mapDim*mapDim); i++){
            if(bossLocation == i){
                mapArray[] = 3;
                i++;
            }
 
            mapArray[] = rand()%2 + 1;    // when you try to write into memory here...
                                          // you may buffer overflow because you did
                                          // not correctly size your mapArray
    }

your solution:
    printf("Enter your desired map size:\n");//Only works for 3 or 2 for some reason
    scanf(" %d", &mapDim);
    int mapArray[mapDim*mapDim];    // declare and size your array after reading in size
                                   // of your mapDim variable to ensure correct value
0 Ben Norris · January 20, 2015
Thanks! Sorry I posted this to reddit to and luckily they found the solution! 
  • 1

C

107,073 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator