[英]C accessing a 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++;
}
编辑:我的问题是我应该如何能够在需要的地方访问该数组?
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++;
}
看起来您想在循环迭代之间保留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++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.