C访问可变长度数组

时间:2014-05-01 13:20:52

标签: c arrays scope dynamic-arrays variable-length-array

我需要访问我在第一行从文件读取时创建的可变长度数组。 为了在我读取以下行时访问数组,我需要在第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++;
}

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

2 个答案:

答案 0 :(得分:2)

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

因此,如果你的fileformat在第一行有总计数,你可以使用动态内存,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++;
}

答案 1 :(得分: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++;
    }
}