这是我的代码,问题是所有单词[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”) 输出:a a b ab abc abc
allwords [0],allwords [1],allwords [2]都具有“ abc”,但是我想要的是:
allwords [0] =“ a”,allwords [1] =“ ab”,allwords [2] =“ abc”
我认为问题出在所有单词的malloc,但是我不知道要怎么解决,有什么建议吗?。
答案 0 :(得分:0)
这是朋友的答案
替换所有单词[c] =单词;
作者:
strcpy(allwords [c],word);
原因:“否则,您将复制指针,并且流程中的单词也会发生变化–”