Thread: How can I avoid overwriting into an array?

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    26

    How can I avoid overwriting into an array?

    I'm reading in a file into an array, but when I print out the first element of the array it's always the last line of the file. How can I avoid doing this?

    Specifically I want to store the lines into each array element. I'm not sure exactly how to explain myself but I hope someone will understand. Here's a sample of my code

    Code:
    while(  j < 8)
    		{ 
    			fgets(storeS,100,dataCar);
    			strcpy(ssheet[i],storeS);
    			printf("%s",ssheet);
    			j++;
    			
    		}
    			
    		printf("%s",ssheet[0]);

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Code:
    while(  j < 8)
    		{ 
    			fgets(storeS,100,dataCar);
    			strcpy(ssheet[i],storeS);
    			printf("%s",ssheet);
    			j++;
    			
    		}
    			
    		printf("%s",ssheet[0]);
    That should probably be j.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    The fact that you are using j as a counter in your loop and using i as an index in your array might have something to do with it.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  4. #4
    Registered User
    Join Date
    May 2011
    Posts
    26
    Oops! I was trying out different things and forgot to change it back. Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Avoid Array crossing boundry
    By jionnet in forum C Programming
    Replies: 3
    Last Post: 03-29-2011, 06:45 AM
  2. avoid duplicates in an ordered array
    By baffleddreams in forum C Programming
    Replies: 1
    Last Post: 09-19-2010, 01:53 AM
  3. Overwriting all in array, why?
    By guesst in forum C Programming
    Replies: 7
    Last Post: 10-09-2008, 05:56 PM
  4. Overwriting Array with New Array
    By Osiris990 in forum C++ Programming
    Replies: 14
    Last Post: 02-25-2008, 01:56 PM
  5. how to avoid duplicate entry to a list/array?
    By janetsmith in forum C Programming
    Replies: 5
    Last Post: 12-17-2006, 09:32 AM