Home > front end >  Why strcpy() copies every string to first index of 2d array
Why strcpy() copies every string to first index of 2d array

Time:10-29

I have a problem with filling a 2d char array with strings from a text file. I am trying to fill 2d array with specific strings from my file, but when I try to print out the first string at position 0 I get all strings connected as if they were one string. I tried it on more simple code and it worked where the strings were declared manually and weren't taken from a file. I've read something about the function itself but couldn't find anything which could couse a problem.

'''

char mer_mod[20], input_mer[20], input_mer_vel[20], data[25]; 
char line[20], time_arr[57][4];
double val_arr[57];
int flag = 0, offsets[5], n=1, j = 0, dates_arr[57], min_date, k =0;

if(strcmp(mer_mod, input_mer_vel) == 0 && flag == 1)  
{
    flag = 0;
    for(int i=0; i<3; i  )
    {
        memset(data,0,sizeof(data)); 
        fgets(data, sizeof data, *pp_file);   
                
        switch (i)
        {
            case 0: val_arr[k] = strtod(data, NULL); break;
            case 1: strcpy(time_arr[k], data); break;
            case 2: dates_arr[k] = atoi(data); break;
        }
    }
    printf("%s\n", time_arr[0]);
    k  ;
}

'''

When I print out string from the array at 0th index I get output from the first picture. In the second picture is output which I desire, but I get this output only if I'm printing the string right after it was added to the array. time_arr is 2d char array, data is a character array where each line from the file gets stored.

enter image description here enter image description here

CodePudding user response:

This

 char time_arr[57][4];

Is an array of 57 elements of size 4

This

 data[25];

Is a string of 25 characters

So this

 strcpy(time_arr[k], data);

is wrong. If data is longer than 3 characters (you have to leave space for the terminator) it will overrun the size of the array element.

Note, based on the results it looks like you just do not have space for the null terminator -- it looks like char time_arr[57][5]; would solve your problem

  • Related