0

First, I'm sorry if another topic is relative to my issue, but I can't reach one which is appropriate.

I will try to be clear as much as possible.

I'm realizing a course project, which need to take about 10 entires text files to save them in an array, then treat the datas. (treating isn't an issue)

I use fgets to get all lines, they I pass the s "string" to an char$ []

Code :

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

int main(int* argc, char* argv[]){
    char* c = "./example.txt";
    char s[500];

    char* lignes[100];
    int sizeLignes = 0;

    printf("%s \n\n", c);

    FILE* myFile = NULL;
    myFile = fopen(c, "r");

    if (myFile != NULL){
        int n;
        while ( fgets(s, 500, myFile) != NULL ){
            printf("%d \n\n", sizeLignes);
            lignes[sizeLignes] = s;
            printf("%s", lignes[sizeLignes]);
            sizeLignes++;
        }

        printf("%s", lignes[1]);
        printf("%s", lignes[2]);
        printf("%s", lignes[3]);

    }else{
        printf("Wrong file");
    }
    fclose(myFile);
    return 0;
}

My s var is good, if I print it every loop, it's good. And if I print lignes[sizeLignes] inside the loop, it's good too. Put if I try to print the value outside... It's like keeping the 4 last words or something like that.

Any idea?

Do you need more informations?

Thanks in advance,

Izio

Izio
  • 378
  • 6
  • 15
  • you need to copy the string into the array. You are only storing the pointer to `s` in the array and then you are overwriting `s` on your next loop iteration. – pstrjds Sep 16 '17 at 14:59

1 Answers1

0

You should use strcpy(lignes[sizeLignes], s) instead of lignes[sizeLignes] = s. You may indeed use strcpy_s too. You also should allocate memory for the string. So I recommend the next code

lignes[sizeLignes] = malloc(500);
strcpy(lignes[sizeLignes], s);

Free the dynamic memory when it will be not required.

vollitwr
  • 429
  • 2
  • 8