【问题标题】:Generating 2-dimensional vla ends in segmentation fault生成二维 vla 以分段错误结束
【发布时间】:2010-05-27 08:45:13
【问题描述】:

从昨天 (seg fault caused by malloc and sscanf in a function) 开始进一步开发代码,我尝试在网上找到的一些教程的帮助下生成 2-dim vla。但我在(*data)[i][j]=atof(p); 遇到分段错误。该程序应该从文本文件中读取矩阵并将其加载到二维数组(列 1-9)和一维数组(列 10)中

[示例代码]

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

const int LENGTH = 1024;

void read_data(float ***data, int **classes, int *nrow,int *ncol, char *filename){
  FILE *pfile = NULL; 
  char line[LENGTH];
  if(!( pfile=fopen(filename,"r"))){
    printf("Error opening %s.", filename);
    exit(1);
  }
  int numlines=0;
  int numcols=0;
  char *p;

  fgets(line,LENGTH,pfile);
  p = strtok (line," ");
  while (p != NULL){
    p = strtok (NULL, ", ");     
    numcols++;
  }
  while(fgets(line,LENGTH,pfile)){
    numlines++;
  }
  rewind(pfile);
  int numfeats=numcols-1;
  *data=(float**) malloc(numlines*sizeof(float*));
  *classes=(int *)malloc(numlines*sizeof(int));
  if(*classes == NULL){
    printf("\nOut of memory.");
    exit(1);
  }

  int i=0;
  while(fgets(line,LENGTH,pfile)){
    p = strtok (line," ");
    for(int j=0;j<numfeats;j++) 
      {
        (data)[i]=malloc(numfeats*sizeof(float));
        printf("%i ",i);
        (*data)[i][j]=atof(p);
        p = strtok (NULL, ", ");
      }
    (*classes)[i]=atoi(p);
    i++;
  }
  fclose(pfile);
  *nrow=numlines;
  *ncol=numfeats;
}  

int main() {
  char *filename="somedatafile.txt";
  float **data2;
  int *classes2;
  int r,c;

  read_data(&data2,&classes2, &r, &c,filename) ;
  for(int i=0;i<r;i++){
    printf("\n");
    for(int j=0;j<c;j++){
      printf("%f",data2[i][j]);
    }
  }
  return 1;
}

[somedatafile.txt 的内容]

50 21 77 0 28 0 27 48 22 2
55 0 92 0 0 26 36 92 56 4
53 0 82 0 52 -5 29 30 2 1
37 0 76 0 28 18 40 48 8 1
37 0 79 0 34 -26 43 46 2 1
85 0 88 -4 6 1 3 83 80 5
56 0 81 0 -4 11 25 86 62 4
55 -1 95 -3 54 -4 40 41 2 1
53 8 77 0 28 0 23 48 24 4
37 0 101 -7 28 0 64 73 8 1
...

【问题讨论】:

  • 如果您实际上要求数据是矩阵,即 n*m 值,这将更容易实现。然后,一旦确定了大小,您就可以对整个矩阵执行一次 malloc()。

标签: c multidimensional-array malloc c99


【解决方案1】:

你是说 (*data)[i]=malloc(numfeats*sizeof(float));

而不是
(data)[i]=malloc(numfeats*sizeof(float))

?

【讨论】:

  • 哦,伙计。你认为你已经检查了每一个组合然后那个。谢谢芯片!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多