c - Why do I always get the last elements of my string array? -


this question has answer here:

i trying read strings text file , save them in array of strings. however, when try print contents of string array last part printed. why code copy last string?

my code

# include <stdio.h> # define buffersize 100  int main(int argc, char *argv[]){    char buffer[buffersize];     int = 0;    char *text[buffersize];     while(fgets(buffer, buffersize, stdin) != null){           text[i] = buffer;           i++;    }     int j = 0;    (j=0; j<sizeof(text)/sizeof(char); i++){           printf("%s\n", text[j]);    }     return 0; } 

my text file

esd can create spectacular electric sparks (thunder , lightning large-scale esd       event), less dramatic forms may neither seen nor heard, yet still large enough cause damage sensitive electronic devices. electric sparks require field strength above 4 kv/cm in air, notably occurs in lightning strikes. other forms of esd include corona discharge sharp electrodes , brush discharge blunt electrodes. 

output

>>> make 1_17; ./1_17 < example.txt m blunt electrodes.  m blunt electrodes.  m blunt electrodes.  m blunt electrodes.  ... 

there 2 issues. first is, text[i] contains same buffer you've used multiple times. second in printing code, you're printing text[0].

using same buffer

there's 1 buffer declared,

char buffer[buffersize]; 

and while modify contents many times in loop, it's same buffer (i.e., same storage area in memory),

text[i] = buffer; 

makes every element of text contain (address of) same buffer. need copy contents of buffer new string , store in text[i] instead. can duplicate string using, e.g., strdup if can use posix functions, in

text[i] = strdup(buffer); 

strdup uses malloc allocate space string, if you're using in larger application, sure free strings later. in simple application, though, they'll freed when application exits, you're not in trouble.

if can use standard c functions, you'll want strcpy make little bit more work. (you'll need allocate string big enough hold current contents of buffer, , copy buffer's contents it. you'll still want free them afterwards.

printing text[0]

however, you've got issue printing code. you're indexing text j, never modifying j (you're incrementing i i++), you're printing same string (which first in array, not last, contents same lsat string read file):

 int j = 0;  (j=0; j<sizeof(text)/sizeof(char); i++){         printf("%s\n", text[j]);  } 

after first loop, i number of strings you've got, want:

int j; ( j=0; j < i; j++ ) {   printf("%s\n", text[j]); } 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -