C - Creation of an array of strings, help request -
C - Creation of an array of strings, help request -
i'm having big problems while creating simple programme in c.
i have next function:
void createstrings (char *dictionary[], int *n) { int i; char word[20]; printf ("insert how many words use: "); scanf ("%d", &(*n)); // initialization (i = 0; < *n; i++) { dictionary[i] = '\0'; } // populating array words (i = 0; < *n; i++) { printf ("insert word in position %d: ", i); scanf("%s", word); dictionary[i] = word; } }
in main read array of words populated using
printf ("following words have been inserted:\n"); (i = 0; < n; i++) { printf ("dictionary[%d] = %s\n", i, dictionary[i]); }
i'm pretty sure lastly cycle has been implemented well.
when run programme , seek insert, example, 3 different words "one" "two" , "zero" next output:
insert how many words use: 3
insert word number 0: one
insert word number 1: two
insert word number 2: zero
following words have been inserted:
dictionary[0] = zero
dictionary[1] = zero
dictionary[2] = zero
it's lastly word inserted gets saved , cycle goes way override other elements of array.
any help appreciated.
char word[20];
single storage location: you're pointing each successive dictionary[i]
same location, overwriting new value. so, array of pointers chunk of memory (which shouldn't access after createstrings
returns anyway, since it's local function).
change
dictionary[i] = word;
to
dictionary[i] = strdup(word);
for smallest possible change.
i can think of more improvements, belong on codereview, , should sufficient create work.
c
Comments
Post a Comment