Search code examples
cc-strings

How to copy single chars from an array of strings to another string in "C"


Here is my code, The problem is that all the strings of allwords[i] change to the same string in the last of the code

My Code:

#include <stdio.h>
#include <string.h>
void print(int size, char *string)
{
    char* word;
    char** allwords;
    word = malloc(size*sizeof(char));
    allwords = malloc(sizeof(char*));
    int c = -1;
    for(int i = 0; i < size; i++)
    {
        if((*(string + i) == *(string))) /* if the start of the string is the same string of the original string */
        {
            for (int j = i; j < size; j++)
            {
                c++;
                int k;
                for (k = 0; k <= j - i; k++)
                    word[k] = string[k];
                for(int s = k; s < strlen(word); s++) /* prevents unknown symbols */
                    word[s] = '\0';
                allwords = realloc(allwords,(c+1)*sizeof(char*));
                allwords[c] = malloc(strlen(word) * sizeof(char));
                allwords[c] = word;

                for(int f = 0; f <= c; f ++) /* Deletes all the similar strings, and keeps only one */
                    for(int t = f + 1; t < c; t++)
                        if(allwords[f] == allwords[t])
                            allwords[t] = '\0';

                printf("%s\n",allwords[c]); /* prints the current string */
                printf("%s\n",allwords[0]); /* To check if allwords[0] has changed or not during the code */
            }
        }
    }
}

Input: (3 , "abc") Output: a a ab ab abc abc

allwords[0] , allwords[1] , allwords[2] , all of them have "abc", but what I want is:

allwords[0] = "a" , allwords[1] = "ab" , allwords[2] = "abc"

I think that the problem is from malloc of allwords, but I don't know what I have to do to fix it, any suggestions ?.


Solution

  • Here is the answer from a friend

    Replacing allwords[c] = word;

    by:

    strcpy(allwords[c] , word);

    Reason: " Otherwise, you are copying pointers, and word changes along your flow – "