【问题标题】:read data from struct into 2d array c将数据从结构读取到二维数组 c
【发布时间】:2014-03-11 21:59:16
【问题描述】:

我正在尝试使用二维数组将坐标绘制到地图上。坐标数据已由用户输入并保存在结构中。这是从我的主程序中取出的代码的 sn-p。

#include <stdio.h>
#include <stdlib.h>

char map[5][10]={
    "..........",
    "..........",
    "..........",
    "..........",
    ".........."
};

struct coord{
    int x;
    int y;
};

int loop, n, i;

struct coord mg[3];

int main(){

    for(loop=0;loop<3;loop++){
        printf("\n\nEnter MAGENTA X coordinate 0:\n");
        scanf("%d",&mg[loop].x);
        printf("\nEnter MAGENTA Y coordinate:\n");
        scanf("%d",&mg[loop].y);
    }

    printf("Struct contains:\n");

    for(loop=0;loop<3;loop++){
        printf("\tx %d,%d y\n",mg[loop].x,mg[loop].y);
    }

    /*AS SUGGESTED IN ANSWER BELOW (PAUL92),I HAVE DONE THIS BUT GET AN ERROR*/ 

    n=3;
    i=0;    

    for (i = 0; i < n; i++) {
         map[mg.y][mg.x] = 'x';
    }

    getchar();
    return(0);
}

我得到的错误是

testing.c:35:13: error: member reference base type 'struct coord [3]' is not a
  structure or union map[mg.y][mg.x] = 'x';
                         ~~^~

我想要实现的是将 struct 中保存的坐标分配给数组中的正确元素,即如果用户输入 3(x),5(y) 则元素 map[4][ 2] 将保持这个显示和'x'。

【问题讨论】:

  • 请使用正确的缩进!
  • 问自己一个问题 - mg 是什么类型?
  • @zoska 我假设 mg 是 int 类型,存储在结构数组中。你有什么建议?
  • mg 的类型是“3 个struct coord 的数组” - 它没有x 成员或y 成员,所以mg.xmg.y 没有存在。数组中的每个单独元素都有这样的成员,所以 mg[i].xmg[i].y 只要0 &lt;= i &lt; 3 就可以了...你在代码的其他部分有这个权利(例如mg[loop].x),所以我不确定你想让map[mg.y][mg.x] 成为什么......
  • 我建议mg 没有xy 属性。为什么要它,因为它是一个数组?我的问题从哪里来 - 当您将 mg 声明为 struct coord mg[3] 时,它是什么类型

标签: c arrays struct multidimensional-array


【解决方案1】:

我不确定我是否完全理解了您想要的内容,但如果您只想在地图上用“x”标记点,您可以遍历这些点:

for (int i = 0; i < n; i++) {
    map[mg.y][mg.x] = 'x';
}

其中 n 是点数。 当然,这是在你初始化地图之后。

【讨论】:

  • 现在我已经看到它写下来了,这很有意义!我将编译并测试它。谢谢@paul92
  • 我已经编辑了我的问题,以反映我按照您的建议实施的内容。我收到了一个错误,已包含在修改后的问题@Paul92
  • 是的!这正是我所追求的!如果我把它放到for(loop); 中,那应该是一种享受! @twalberg
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
相关资源
最近更新 更多