storing strings in arrays

This is a discussion on storing strings in arrays within the C Programming forums, part of the General Programming Boards category; Hi ,
I have one txt file: list1_UT.txt
It contains following image names & UT:
reduced_obj_r_3.fits 21:08:37
reduced_obj_r_5.fits 21:16:20
reduced_obj_r_9.fits ...

1. Read this file: use two variables to read two columns(str1,str2), line by line.
2. Assign these variables to two different arrays (img_L1[ ] and time_L1[ ] )
3. Access these two different arrays whenever I want and from any starting point i.e. e.g. from element 13 onwards.

1. do not use feof to control loop - read FAQ. Use the return value of scanf instead
2. check the return values before using it (for example fopen could fail)
3. provide different starage conainer for each string, for now you writing all strings into the s1 buffer overwriing with the new string the old one. You have 2 choices - make an array of strings
char V1[MAX_STRING_NUM][MAX_LENGTH]
or leave an array of pointers as you have now - but allocate the storage space fo each sring wih malloc before copying it.

Do you see the difference? strcpy copies the values of the array s1 to a NEW array that img_L1[i] points. The second will make img_L1[i] POINT to s1. So s1 and img_L1[i] will point to the same memory.
So you change that memory. img_L1[i] still points to the same changed memory.
Do you get the difference?? You are not using pointer logic correctly.

2) If you fix the above you will get an error if you don't allocate memory. That is why you have to use char img_L1[22][25], where 22 the number of lines and 25 the maxiumum number of characters a string has (that you use for s1).

You can also do for (int i = 0; i < 22; ++i) imgL1[i] = malloc(25); to dynamically allocate memory, but that is worse in your case.

3) read the faq as vart said and you will see why you get reduced_obj_r_41.fits twice.

EDIT: I forgot the most important part! You get the same thing because all pointers of img_L1 point to the same location. s1, which after the loop has the value of the last element

> Please run my code. Then it will be clear what I want to say exactly.
> There is no problem in reading the file.
1. You've edited the code so badly that it won't compile, nevermind run.
2. We don't need to compile or run things just to spot bugs. Just because you haven't noticed there's a problem doesn't mean there isn't a problem.