【问题标题】:Programm is stuck while allocating space for a 2d array程序在为二维数组分配空间时卡住
【发布时间】:2018-04-09 00:13:38
【问题描述】:

大家好,我有一个问题,我需要为二维数组分配空间,但不知何故卡住了。之后它应该进入一个 for 循环,但它永远不会到达那里。有人知道为什么吗?

  int len = read_file("staedte.csv", staedte, laender, bewohner);

  char **resultat;
  int resultatzaehler = 0;
  resultat =(char **) malloc (100 * sizeof(char));
  if(resultat == NULL){
    printf("Malloc failed to allocate space");
    exit(1);
  }
  for(int i = 0; i < 100; i++){
    resultat[i] =(char *) malloc (100);
    if(resultat[i] == NULL){
      printf("Malloc failed to allocate spacce 2");
      exit(1);
    }
  }

【问题讨论】:

  • 你怎么知道卡在哪里?
  • resultat =(char **) malloc (100 * sizeof(char)); -> resultat =(char **) malloc (100 * sizeof(char*));
  • resultat =(char **) malloc (100 * sizeof(char *)); ?
  • @OliverCharlesworth 我用一些 printf 命令预先测试了它,看看它在卡住之前能走多远。致其他人:非常感谢这是解决方案!:)
  • resultat = malloc(100 * sizeof(*resultat))

标签: c arrays string malloc allocation


【解决方案1】:

你应该使用分配

resultat = (char**) malloc(100 * sizeof(char *))
for(i = 0; i < 100; i++) {
resultat[i] = (char*) malloc(100 * sizeof(char))
}

【讨论】:

  • 或者更好,resultat = malloc(100 * sizeof *resultat);resultat[i] = malloc(100);
  • sizeof(char) == 1 定义。
猜你喜欢
  • 2017-03-15
  • 2016-04-19
  • 2017-06-03
  • 2020-09-05
  • 2015-02-01
  • 2015-06-12
相关资源
最近更新 更多