Question

I m trying to make a piece of code that prompts the user for a number of string, n, dynamically allocates an array of n strings, and then prompts the user to enter n strings.

The problem I am having is the array is only showing itself being filled with the last string the user entered.

Example: Program prompts user for n User enters 3. User enters "test1" for the first element in the array User enters "test2" for the second element in the array User enters "test3" for the third element in the array

I go to print the contents of the array, and it says each element is "test3"

Here is the code: (flush_buffer() and strip_newline() are functions I wrote that are unimportant to the problem I am having)

printf("How many strings?\n");
scanf("%d", &max_strings);
flush_buffer();

string_array = (char**) malloc(max_strings * sizeof(char*));

for(i = 0; i < max_strings; i++)
{
    scanf("%s", temp);

    strip_newline(temp);

    string_array[i] = temp;

    printf("string_array[%d] is: %s\n", i, string_array[i]);
}
    for(i = 0; i < max_strings; i++)
{
    printf("i: %d\n", i);
    printf("string_array[%d] is: %s\n", i, string_array[i]);
}

Any ideas on what I am missing here?

Was it helpful?

Solution

With the assignment

string_array[i] = temp;

you make all pointers in string_array point to the same place.


I suggest you use strdup to duplicate the string instead:

string_array[i] = strdup(temp);

Of course, this means you have to free all strings in the collection.

OTHER TIPS

When you assign the strings:

string_array[i] = temp;

you just store a pointer of the temporary buffer in each string, which will be overwritten after the next string is read. In other words, all of your strings have the same value, namely temp, which has the contents of the last string read.

If you want to store your strings, you must allocate memory for string_array[i] and then copy the contents with strcpy. Alternatively, you can use a shortcut:

string_array[i] = strdup(temp);

Note that strdup allocates memory internally that you must free() at some point.

you can use this code:

int max_strings;
printf("How many strings?\n");
scanf("%d", &max_strings);

//allocate memory
char **string_array = (char**) malloc(max_strings * sizeof(char*));
for (int i = 0; i < max_strings; i++)
{
    string_array[i] = (char*)malloc(sizeof(char) * 50);
}

for(int i = 0; i < max_strings; i++)
{
    scanf("%s", string_array[i]);

    printf("string_array[%d] is: %s\n", i, string_array[i]);
}
for(int i = 0; i < max_strings; i++)
{
    printf("i: %d\n", i);
    printf("string_array[%d] is: %s\n", i, string_array[i]);
}

//free memory
for (int i = 0; i < max_strings; i++)
{
    free(string_array[i]);
}
free(string_array);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top