Read line by line from a file into an array

I am trying to read line by line in a file and store each line in a position in my array. Here is my attempt but it doesn't give me an error rather it crashes my .exe What am I doing wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
    int n,i, j, k, m;
    char* *strArray;
    char readarray[10];
    FILE *f;
    n=4;
    f=fopen("text.txt","r");
    strArray = calloc(n, sizeof(char*));
    i=0;
    while(fscanf(f,"%s",readarray)!=EOF){
        strArray[i]= calloc(200, sizeof(char));
        strArray[i] = readarray;
        i++;
    }


    printf("%s", strArray[1]);

    return 0;
}
11
12
13
14
15
    while(fscanf(f,"%s",readarray)!=EOF){ //put a width limit
        strArray[i]= calloc(200, sizeof(char));  //why 200? readarray only has 10
        strArray[i] = readarray; //just lost the allocated memory (try strcpy)
        i++;
    }
Well thats was 200 because I copied it out of a different project. Anyway I updated the code but it is still crashing. Here is my new while statement:

1
2
3
4
5
    while( (fgets(readarray, 25, f))!=NULL){
        strArray[i]= calloc(10, sizeof(char));
         strcpy(strArray[i],readarray);
        i++;
    }
while( (fgets(readarray, 25, f))!=NULL){ // 25>10
You could avoid the memory management with std::string
Topic archived. No new replies allowed.