简体   繁体   中英

Filling an array of structs and allocating memory on the heap

I am creating what used to be an object oriented program into the same program but written in C which I have no experience in but am learning slowly. My question revolves around my first step which is to have an array of structs that I call rooms on the heap. As well ass filling the array inside the struct with creatures that move from room to room. My problem so far is trying to fill the rooms variables with info read in from stdin. The amount of rooms first(size of my array), and then the state(clean or dirty) and whether or not the room has neighbors(the rooms that have neighbors will be connected in the conditional statements once I can fill the array first), these however are all integers. I was previously given advice to have a global pointer to the array and add the info that way as it is scanned in. I believe I might be close? But no matter what I am trying I get a segmentation fault right after the 5 ints are scanned in. I am very new to this and learning as fast as I can for an upcoming due date for my project in C. Any advice or help at all would be greatly appreciated. My code is below

#include <stdio.h>
#include <stdlib.h>
typedef struct {
int type;
int room_number;
int creat_number;
} creature;

struct room;

typedef struct {
struct room *north; //refernce to neighbor
struct room *south;
struct room *east;
struct room *west;
int room_name, state;
creature creature_array[100];
} room;
room *ptr;
int respect = 40;

int main(void) {
int room_name, state, north, south, east, west;
printf("Welcome!\n");
printf("How many rooms?\n");
int num_r;
scanf("%d", &num_r);
ptr = malloc(num_r * sizeof (room));
int i = 0;
for (; i < num_r; i++) {
    scanf("%d", "%d", "%d", "%d", "%d", &state, &north, &south, &east, &west);
    (ptr + i)->room_name = i;
    (ptr + i)->state = state;
     (ptr+i)->north=north;
     (ptr+i)->south=south;
     (ptr+i)->east=east;
     (ptr+i)->west=west;
    if (north != -1) {

    }
    if (south != -1) {

    }
    if (east != -1) {

    }
    if (west != -1) {

    }

}

Only first argument of scanf is used as "format", meaning that your

scanf("%d", "%d", "%d", "%d", "%d", &state, &north, &south, &east, &west);

is interpreted as "for formatter "%d" get first argument and interpret is as an int". So your second "%d" is interpreted as int (as it's passed as pointer to string array it compiles), other arguments are ignored .

Use :

scanf("%d %d %d %d %d", &state, &north, &south, &east, &west);

Also build your code with warnings enabled! This will catch some nasty errors like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM