Home > Mobile >  Having issues with array holding its value
Having issues with array holding its value

Time:12-09

I am kind of new when it comes to C. Took a class on it in college but I just don't practice it much. Well my issue that I'm having is that I'm trying to take an text file and convert it into an array. I have been able to get the text file and print it into the console but when I save run the while statement to read each line, my whole array gets overwritten. For instance if my last line on my text file is 19, my array[0] gets over written to what should be on array[18].

I know the indentations are off a off, coding is a mess, and forgive me on the printf commands, I'm only using them to troubleshoot my code. The text file will have IP address on each line.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

 
#define MAX_LINE_LENGTH 16

 
int main()
{
    int lineCntPOSlist = 0;
    int lineCnt = 0;
    int i = 0;
    FILE    *textfile;
    char    line[MAX_LINE_LENGTH];
    char* posList[50];
    
    textfile = fopen("pos-list.txt", "r");
    
    if(textfile == NULL)
    {
        int posListExist = 0;
        system("cls");
        printf("File Exist %d\n", posListExist);
        fprintf(stderr, "**File open failed\n Make sure there is a pos-list.txt file");
        return 1;
    }
    
    system("cls");
    
    while(fgets(line, MAX_LINE_LENGTH, textfile))
    {
        printf("Line %d: %s",lineCnt , line);
        posList[lineCnt] = line;
        printf("posList[%d] = %s\n", lineCnt, posList[lineCnt] );
    printf("posList[0] = %s\n", posList[0] );
        
        lineCnt =   lineCnt;
        lineCntPOSlist =   lineCntPOSlist;
    }
    fclose(textfile);
    return 0;
}

CodePudding user response:

This:

posList[lineCnt] = line;

simply sets posList[lineCnt] to point at the line buffer in line, it copies zero characters of actual data. In higher-level languages where strings have a bit more presence, this would make sense, but in C it doesn't.

Since there is only one line buffer, it will always hold the characters making up the most recently loaded line, and thus it will act as if previous lines are being "overwritten".

There are several solutions, here are a few:

  • Make posList into a proper array of strings, but that requires you to decide max length in advance and will waste the space for shorter lines.
  • Use something like strdup() to allocate copies on the heap of each line, and store pointers to those.
  • Use a more "proper" reallocating array for the storage and store line pointers (or offsets, which might be better suited due to the reallocating) in the array for easier access.
  •  Tags:  
  • c
  • Related