Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!cs.utexas.edu!sun-barr!newstop!sun!amdcad!dgcad!dg-rtp!snaggle!barnettr From: barnettr@snaggle.rtp.dg.com (Richard Barnette) Newsgroups: comp.lang.c Subject: Re: reading from a file.sorting Keywords: files/sorting Message-ID: <1991Apr4.182011.14212@dg-rtp.dg.com> Date: 4 Apr 91 18:20:11 GMT References: <1991Apr3.090427.25624@milton.u.washington.edu> <1991Apr3.100911.29842@milton.u.washington.edu> Sender: usenet@dg-rtp.dg.com (Usenet Administration) Organization: Data General Corporation, RTP, NC. Lines: 51 In article <1991Apr3.100911.29842@milton.u.washington.edu> amigo@milton.u.washington.edu (The Friend) writes: >>amigo@milton.u.washington.edu (The Friend) writes: >> >> > I'm looking for a simple program that'll read ten words from a > string that has only got spaces between the words. I > had one example that had pointers - data read in via fscanf, > then the pointer was copied to another pointer array (each array > held one word). After the 10 words were read, the array was simply > incremented backwards in a for loop to print out correctly. >> > I have [REVISED]: >> >> > FILE *fp; > static char *data_array[11]; > int i; > main(){ > fp=fopen("test","r"); > for(i=0;i<10;i++){ > fscanf(fp,"%s", data_array[i]); > printf("%d %s",i,data_array[i]); /* test to see >> anything's put in data_array[] */ > } >> The pointers in data_array are all NULL; they don't point to anything. In order save the data read by fscanf() you'll need to allocate space. Try this #include FILE *fp; static char *data_array[11]; int i; main(){ char data[32]; /* 31 letters in word + null byte */ fp=fopen("test","r"); for(i=0;i<10;i++){ fscanf(fp,"%s", data); data_array[i] = strdup(data); } strdup() is a standard library function declared in string.h Note also, data_array will hold 11 items, but the for loop will only initialize 10 of them; the 11th is unused. Richard Barnette | Data General Corporation | obligatory (in)famous quote: (919) 248-6225 | RTP, NC 27709 | You wascal wabbit! Commercial Languages | 62 T.W. Alexander Drive | Wandering wizards won't barnettr@dg-rtp.dg.com | win! - /usr/lib/sendmail