【问题标题】:Allocating array of struct pointers? [duplicate]分配结构指针数组? [复制]
【发布时间】:2014-05-13 12:43:08
【问题描述】:

我找不到确切问题的答案,因为条件更具体一点: 如何分配结构指针数组。

typedef struct COORDS
{
  int xp;
  int yp;
} coord;

coord** xy;

我想像这样分配它:xy[500][460] 但是访问它们时会返回无效的内存错误。

【问题讨论】:

  • 对于初学者,new 是保留字。您是尝试在堆中分配还是在堆栈中声明它?
  • 编译器是旧的,它真的很旧 C. new 在我的例子中不是保留字,但我会编辑这个例子。
  • new 只是 C++ 中的保留字
  • @Amarghosh new 在 c++ 中保留,但在 c 中不保留(此问题已标记)。话虽如此,避免在 c 中使用 c++ 关键字仍然是一个非常好的主意。
  • @mah 我认为在 C 中使用 c++ 关键字是个好主意;它会提醒不小心在您的代码上使用 C++ 编译器的人

标签: c arrays pointers struct malloc


【解决方案1】:
coord** new = malloc (500 * sizeof (coord*));
int idx = 0;

for(; idx < 500; ++idx)
    new [idx] = malloc (460 * sizeof (coord));

【讨论】:

  • 很抱歉。但它再次给出了同样的错误,使用这个代码。访问权限为:xy[1][2].xp = 20;
  • @Lively:你的代码编译时没有警告吗?
  • 它是来自游戏引擎的非常古老的内置编译器。 @barak manos 发布的代码..work'd 然而。
【解决方案2】:

静态分配:

coord xy[500][460];

动态分配:

coord** xy = (coord**)malloc(sizeof(coord*)*500);
for (int i=0; i<500; i++)
    xy[i] = (coord*)malloc(sizeof(coord)*460);

// and at a later point in the execution of your program
for (int i=0; i<500; i++)
    free(xy[i]);
free(xy);

【讨论】:

  • @Lively:不客气 :)
猜你喜欢
  • 1970-01-01
  • 2021-12-14
  • 2020-05-17
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 2012-07-10
  • 1970-01-01
相关资源
最近更新 更多