0

I was tryin to read a text file and return two dimensional char array to main function. The text file ips.txt as following:

hello1
hello2
hello3

My code as following:

define BUF 20
define TOT 3

char ** getIps(){
    char line[TOT][BUF];
    FILE *plist = NULL;
    int i = 0;
    int total = 0;

    plist = fopen("ips.txt", "r");
    while(fgets(line[i], BUF, plist)) {
        line[i][strlen(line[i]) - 1] = '\0';
        i++;
    }
    return line;

}

int main(void) {
    int i=0;
    char (*line)[TOT];
    line=getIps();
    int total=3;
    for(i = 0; i < total; ++i)
        printf("%s\n", line[i]);

    return 0;
}

The main function print out nothing, Not sure where I did wrong?

Jack
  • 5,540
  • 13
  • 65
  • 113
  • 3
    1. check your return value of `fopen`, 2. you can't return the address of a local variable, 3. why is total assigned to 3 in main? – MFisherKDX May 14 '19 at 00:08
  • Your compiler should have warned you that `chat **` is not synonym of `char[3][20]`. If using GCC/Clang, you could use `-Wall -Wextra`. On other compilers, read the documentation – alx - recommends codidact May 14 '19 at 00:09

1 Answers1

1

getIps is allocating line as a local variable. You can’t return a local variable that way; that memory is freed as soon as the function exits.

Also, you’re allocating line as a two-dimensional array of char, but the caller is trying to map that onto a one-dimensional array of pointers to char. Again, this doesn’t work.

getIps could instead allocate a similar array of pointers, and use malloc to allocate space for each string. However, since the caller has already started doing that, it’s simpler to just pass the address to getIps and have it use that.

There are other issues. The code assumes there will only be three lines of input; if there are more, you will overrun the buffer. You’re hardcoding things that should use #define, such as int total=3. You don’t check the return value of fopen.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
  • I should rename the variable line to line2 or other, I already realized it before posting it. I still didn't get your point, can you help me modify one or two code please. – Jack May 14 '19 at 00:28
  • Thank you so much! I just got understood your answer, Maybe I'm a many years Java guy, I can't switch my brain shortly. btw, I will close this question because I had a similar one. sorry about that and thank you again! – Jack May 14 '19 at 04:22