c - C中的结构矩阵

标签 c matrix struct

如何制作结构矩阵或结构指针矩阵?矩阵 a 中的元素应该是 Area 类型的结构。

到目前为止,这是我尝试过的:

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

typedef struct {
  char type_toy[20];
  int nr;
  char town[20];
  char direction;
} Area;

void AllocMatrix(int N, int M, Area** a) {
  int i;
  a = malloc(N * sizeof(Area *));
  for (i = 0; i < N; i++) {
    a[i] = calloc(M, sizeof(Area*));
  }
}

int main() {
  int N, M;
  Area** a;
  printf("N = ..., M = ...");
  scanf("%d %d", &N, &M);
  AllocMatrix(N, M, a);

  for (i = 0; i < N; i++) {
    for (j = 0; j < M; j++) {
      scanf ("%s", &a[i][j].town);
      scanf ("%s", &a[i][j].type_toy);
      scanf ("%d", &a[i][j].nr);
      scanf ("%s", &a[i][j].direction);
    }
  }
  return 0;
}

最佳答案

void AllocMatrix(int N, int M, Area** a) {

应该是Area***,否则指针的按值传递副本将保存分配内存的地址,调用函数将无法获取它。

进一步,

a[i] = calloc(M, sizeof(Area*));

应该是 sizeof(Area),如果我的第一点适用,它应该是 (*a)[i] =

关于c - C中的结构矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27572941/

相关文章:

c++ - 如何将 IP 地址转换为 MAC 地址

python - 如何向大 numpy 矩阵添加列

c#调用c++ dll传输struct array发生异常

c++ - lu_factorize 返回什么?

algorithm - 用特定条件填充矩阵

c++ - ... union 问题中不允许使用构造函数

c++ - Arduino 上的结构 : function() 'does not name a type'

c - 反对 C 代码中变量冗余的有力论据是什么

C - 逐行读取文件的最佳方法

c++ - 如何以一种不错的方式禁用 OpenMP 指令?