c - 填充结构数组并在堆上分配内存

标签 c arrays struct malloc

我正在将以前的面向对象程序创建到同一个程序中,但用 C 编写,我没有经验,但正在慢慢学习。我的问题围绕着我的第一步,即拥有一个我称之为堆上的房间的结构数组。以及用从一个房间移动到另一个房间的生物填充结构内的数组。到目前为止,我的问题是尝试用从标准输入读取的信息填充房间变量。首先是房间的数量(我的数组的大小),然后是状态(干净或肮脏)以及房间是否有邻居(一旦我可以先填充数组,有邻居的房间将在条件语句中连接) ,但是这些都是整数。之前有人建议我有一个指向数组的全局指针,并在扫描时以这种方式添加信息。我相信我可能会接近吗?但无论我尝试什么,在扫描 5 个整数后,我都会遇到段错误。我对此非常陌生,并尽快学习 C 语言项目即将到来的截止日期。任何建议或帮助所有人将不胜感激。我的代码如下

#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) {

    }

}

最佳答案

只有 scanf 的第一个参数被用作“格式”,这意味着您的

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

被解释为“对于格式化程序 "%d" 获取第一个参数并解释为 int”。因此,您的第二个 "%d" 被解释为 int (因为它作为指向它编译的字符串数组的指针传递),其他参数被忽略

用途:

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

还可以在启用警告的情况下构建代码!这会捕获一些类似的令人讨厌的错误。

关于c - 填充结构数组并在堆上分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25687166/

相关文章:

c - 使用 UDP 套接字的多个 sendto()

javascript - 从 JavaScript 更新属性并删除数组中的重复元素

C - 结构内的函数

c - 在 c 中为跨平台 (Linux) 编译代码时出错

将 Long 转换为 Unsigned Short Int/Strtol

java - java 访问数组

c - C 中的图结构

c - 为什么以及何时在 C 编程中使用静态结构?

无法成功传递/返回结构指针

javascript - 在javascript中解析json