Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何替换结构中的字符串中的字符?_C - Fatal编程技术网

C 如何替换结构中的字符串中的字符?

C 如何替换结构中的字符串中的字符?,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

如果问题之前已经回答过,请道歉。我找不到任何帮助

我的任务是创建一个函数,该函数在参数中采用一个结构(包含一个字符串),并替换该字符串中的一个字符。现在我正试图用字母“J”替换空格,但我遇到了一些困难

这是我的密码:

函数h

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");