如何正确迭代结构数组?

时间:2017-01-25 20:30:49

标签: c arrays struct

我已经看到了这方面的几个主题,但我仍然不明白为什么我遇到了通过我的struct数组的问题。

所以我有一个带有两个typedef结构的头文件,我在我的c源代码中使用它:

typedef struct Point{
    int y;
    int x;
} point;

typedef struct Room{
    point top_left;
    point top_right;
    point bottom_left;
    point bottom_right;
} room;



#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "dungeon.h"

#define HEIGHT 105
#define WIDTH 160

int randomSeed();
void createDungeon();

int main() {
    createDungeon();
    return 0;
}

void createDungeon(){
    char dungeonGrid[HEIGHT][WIDTH];
    room *rooms = malloc(10 * sizeof(room));
    int i,y,x;
    int a;

    for(i = 0; i < 10; i++){
        srand(randomSeed());
        int height = (rand() % (10 + 1 - 5)) + 5;
        int width = (rand() % (15 + 1 - 7)) + 7;

        int randomY = (rand() % (105 + 1 - 0)) + 0;
        int randomX = (rand() % (160 + 1 - 0)) + 0;

        rooms[i].top_left.y = randomY;
        rooms[i].top_left.x = randomX;
        rooms[i].top_right.y = randomY;
        rooms[i].top_right.x = randomX + width;
        rooms[i].bottom_left.y = randomY + height;
        rooms[i].bottom_left.x = randomX;
        rooms[i].bottom_right.y = randomY + height;
        rooms[i].bottom_right.x = randomX + width;

    }

   for(y = 0; y < HEIGHT; y++){
        for(x = 0; x < WIDTH; x++){
            dungeonGrid[y][x] = ' ';
        }
    }

    for(y = 0; y < HEIGHT; y++){
        for(x = 0; x < WIDTH; x++){
            for(a = 0; a < 10; a++){
                if(rooms[a].top_left.y <= y  &&  y <= rooms[a].bottom_left.y && rooms[a].top_left.x <= x  && rooms[a].top_right.x >= x){
                    dungeonGrid[y][x] = '.';
                }
            }
        }
    }


    for(y = 0; y < HEIGHT; y++){
        for(x = 0; x < WIDTH; x++) {
            printf("%c", dungeonGrid[y][x]);
        }
        printf("\n");
    }

}

in

t randomSeed(){
    srand(time(NULL));
    int randNum = (rand() % (100000 + 1 - 0)) + 0;
    return randNum;
}

我想做的事情:基本上我制作了一个大小为105x160的地牢,里面有随意大小的房间。这些房间将在终端中显示为一组使用角色的行和列。&#39;我基本上使用for循环在地牢网格上找到随机x和随机y,并将其作为我的起点放置房间。我也使用rand()来获得随机的高度和宽度。最小高度和宽度需要为7x5,我只选择一个任意数字作为它应该的最大尺寸。

问题:我检查了房间结构(*房间)的指针,发现在房间[0 - 9],top_left,top_right等的所有点都完全一样数字,它不应该是。

我的问题:如何正确迭代我的struct数组,以便每个房间有不同的坐标?也许我调用rand()的方式有问题?我做了一个获取各种随机数的方法,我认为我的for循环会调用该方法并且每次都给出一个随机数,所以每个房间的坐标都不同。

0 个答案:

没有答案
相关问题