【问题标题】:C accessing a variable length arrayC访问可变长度数组
【发布时间】:2014-06-17 23:33:28
【问题描述】:

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

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

【问题讨论】:

  • 思考:是否有可能回答一个不知道答案的问题?
  • 省略号,你不能这样使用VLA。使用动态内存 (malloc) 和指向数组开头的指针。此外,您不应该在分配(声明)之前写入数组。将信息存储在其他地方。
  • 我们和编译器都不是通灵的,它不会改变 VLA 在范围内的大小。它怎么知道它是否可以复制东西?
  • 如果您喜欢问题中显示的示例代码,那么变量word 在定义它的范围内是本地的,并且只能在该范围内访问。
  • 我并没有特别询问如何做不可能的事情。更像是有任何其他方法,例如@osgx 提到的我将要研究的方法。

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


【解决方案1】:

看起来您希望在循环迭代之间保留 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++;
    }
}

【讨论】:

  • 我将此标记为正确答案,因为它在第一次实施时对我很有效。
【解决方案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++;
}

【讨论】:

  • 感谢您的回答,但我在尝试时遇到了分段错误,而其他解决方案似乎第一次工作。
猜你喜欢
  • 2013-06-23
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 2018-12-16
  • 1970-01-01
相关资源
最近更新 更多