如何将字符串数组中的单个字符复制到 "C" 中的另一个字符串

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

这是我的代码,问题是在代码的最后

,allwords[i]的所有字符串都变成了同一个字符串

我的代码:

#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] = '[=11=]';
                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] = '[=11=]';

                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 */
            }
        }
    }
}

输入:(3 , "abc") 输出:a a ab ab abc abc

allwords[0] , allwords[1] , allwords[2] , 都有"abc" , 但是我要的是:

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

我认为问题出在 allwords 的 malloc,但我不知道我必须做些什么来解决它,有什么建议吗?。

这是朋友的回答

替换所有单词[c] = 单词;

作者:

strcpy(所有单词[c], 单词);

原因:“否则,您正在复制指针,并且单词会随着您的流程发生变化 –”