Question

I need to access a variable length array i have created on the first line reading from a file. In order to access the array for when i am reading the following lines i would need to initialize it before line 1 is read out side of my conditional statement. but this is before I know the length of the array.

here is an example of my code

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++;
}

Edit: My question is how should i go about being able to access this array where i need it?

Was it helpful?

Solution

Looks like you want contents of word array to be preserved between loop iterations. This means, you must put the array to the scope outside the loop. In your question code, you want to determine size inside the loop, so you'd essentially need to redefine the size of VLA, which is not possible. You can do this by using malloc as shown in another answer, but looking at your code, it's better to duplicate your call to fgets, allowing you to move the definition of VLA outside your loop, something like:

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++;
    }
}

OTHER TIPS

VLA arrays can't be accesses outside of the scope where they are declared (the scope is inside { } symbols).

So, if your fileformat has the total count in first line, you can use dynamic memory, and malloc your array:

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++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top