0

我需要访问我在从文件读取的第一行创建的可变长度数组。为了在我阅读以下行时访问该数组,我需要在第 1 行被读出我的条件语句之前对其进行初始化。但这是在我知道数组的长度之前。

这是我的代码示例

int count=0;
while (fgets(line, sizeof(line), fd_in) != NULL) {
  if(count==0){
    //get wordcount from line
    int word[wordcount];
    //put line data into array, using strtok()
  }else{
    //need to access the array here
  }
  count++;
}

编辑:我的问题是我应该如何才能在我需要的地方访问这个数组?

4

2 回答 2

2

看起来您希望word在循环迭代之间保留数组的内容。这意味着,您必须将数组放在循环之外的范围内。在您的问题代码中,您想确定循环内的大小,因此您基本上需要重新定义 VLA 的大小,这是不可能的。您可以使用malloc另一个答案中所示的方法来执行此操作,但是查看您的代码,最好将您的调用复制到fgets,从而允许您将 VLA 的定义移到循环之外,例如:

if(fgets(line, sizeof(line), fd_in) != NULL) {
    //get wordcount from line
    int word[wordcount];
    //put line data into array, using strtok()
    int count = 1; //  start from 1 per your question code, is it right?
    while(fgets(line, sizeof(line), fd_in) != NULL) {
        //need to access the array here
        count++;
    }
}
于 2014-05-01T14:33:26.903 回答
2

VLA 数组不能在声明它们的范围之外进行访问(范围在{ }符号内部)。

因此,如果您的文件格式在第一行中有总数,则可以使用动态内存和malloc数组:

int *words = NULL;
int count=0;
while (fgets(line, sizeof(line), fd_in) != NULL) {
  if(count==0){
    int wordcount = ...  //get wordcount from line
    //Allocate the memory for array:
    words = (int*) malloc( wordcount * sizeof(int) );
    //put line data into array, using strtok()
  }else{
    //need to access the array here
    words[count-1] = ....
  }
  count++;
}
于 2014-05-01T13:33:32.267 回答