C 如何替换结构中的字符串中的字符?
如果问题之前已经回答过,请道歉。我找不到任何帮助 我的任务是创建一个函数,该函数在参数中采用一个结构(包含一个字符串),并替换该字符串中的一个字符。现在我正试图用字母“J”替换空格,但我遇到了一些困难 这是我的密码: 函数hC 如何替换结构中的字符串中的字符?,c,C,如果问题之前已经回答过,请道歉。我找不到任何帮助 我的任务是创建一个函数,该函数在参数中采用一个结构(包含一个字符串),并替换该字符串中的一个字符。现在我正试图用字母“J”替换空格,但我遇到了一些困难 这是我的密码: 函数h typedef struct item item; struct item { char * word; }; void space(item * item, char letter); 职能c void space(item * item, char lett
typedef struct item item;
struct item {
char * word;
};
void space(item * item, char letter);
职能c
void space(item * item, char letter) {
char * mot = item->word;
int size = strlen(item->word);
printf("\n\n%s\n\n",mot);
for(int i=0; i<=size; i++) {
if(mot[i] == ' ') {
mot[i] = letter;
}
}
printf("\n\nNEW WORD: ");
printf("%s",mot);
printf("\n\n");
}
下面是我得到的错误:
Seg故障 您正在
malloc
为结构填充空间,但不为结构内的字符串填充空间
item * item = malloc(sizeof(item));
item->word = malloc(sizeof(char) * MAXSTRINGSIZE); //add this line or something similar
strcpy(item->word, "this is a word");
所有这些只会泄露分配。sizeof(char)是1。或者只是
item->word=strdup(“这是一个单词”)代码>并为自己保存一行。@CarlNorum假设您在POSIX系统上…@CarlNorum包含您分配的类型更具可读性。我想这取决于您问谁sizeof(char)
肯定不是惯用法。
item * item = malloc(sizeof(item));
item->word = malloc(sizeof(char) * MAXSTRINGSIZE); //add this line or something similar
strcpy(item->word, "this is a word");