繁体   English   中英

如何将单个字符从字符串数组复制到“ 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] = '\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 */
            }
        }
    }
}

输入:(3,“ abc”) 输出:aa ab ab abc abc abc

allwords [0],allwords [1],allwords [2]都具有“ abc”,但是我想要的是:

allwords [0] =“ a”,allwords [1] =“ ab”,allwords [2] =“ abc”

我认为问题出在所有单词的malloc,但是我不知道该怎么做才能解决它,有什么建议吗?

这是朋友的回答

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

通过:

strcpy(allwords [c],word);

原因:“否则,您正在复制指针,并且单词流随之变化–”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM