Genaro Longoria
Genaro Longoria

Reputation: 13

char array keeps the last element stored

I have written a code to read strings from a file and store them in a char array. The problem is that when I print the strings previously stored I just get that every element of the array has the same information stored at the end of the while loop.

The problem is with the arrays "ori" and "des". After the while loop I print the information in them but I just get the last item stores repeated again and again.

Here is the code:

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

int main() {

FILE *f;

int sale[31];
int llega[31];
char* ori[31];
char* des[31];
int i;
int j;
char string1 [31];
char string2 [31];
char string3 [31];
char string4 [31];

f=fopen("rol.txt","rt");
i = 0;
while((fscanf(f,"%[^\t]\t%[^\t]\t%[^\t]\t%[^\n]\n", string1, string2, string3, string4 ))!= EOF){

    printf( "%s\t%s\t%s\t%s\n", string1, string2, string3, string4 );
    sale[i] = strtol(string1, NULL, 10);
    llega[i] = strtol(string4, NULL, 10);   

    ori[i] = string2; //Here is where I think I am storing the value of string2
    des[i] = string3; //Here is where I think I am storing the value of string3     
    i++;            
}

for (j = 0; j < 31; j++ ){      
    printf("%s %s %d\n",ori[j],des[j],j); //Here for every "j" I get the same result    
}   
fclose(f);

return 0;
}

Upvotes: 1

Views: 1466

Answers (1)

Kaidul
Kaidul

Reputation: 15885

Yes. It is an expected behavior as char* ori[31] is a array of character pointer. The statement ori[i] = string2(ori[i] = &string2[0] both are similar thing) assigns the address of string2. So all ori[i] will contain the content of what string2 holds now (In this case, it is the last assignment of while loop).

Using array of strings

create array of char string:

char ori[31][31];
char des[31][31];

And assign like

strcpy(ori[i], string2);
strcpy(des[i], string3);

Or...

Using std::string ( If you're using C++ )

You can use:

string ori[31];
string des[31];

and

ori[i] = string(string2);
des[i] = string(string3);

and print as printf("%s\t%s\n", ori[j].c_str(), des[j].c_str())

Also you need to import header <string>

Upvotes: 1

Related Questions