2016-09-22 71 views
-3

道歉,如果問題已經回答過。我找不到任何幫助。如何替換結構中字符串中的字符?

我的任務是創建一個函數,該函數在參數中使用一個結構(它包含一個字符串),並替換該字符串中的一個字符。現在我試圖用字母'J'替換空格,但是我遇到了一些困難。

繼承人我的代碼:

func.h

typedef struct item item; 
struct item { 
    char * word; 
}; 

void space(item * item, char letter); 

func.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"); 
} 

的main.c

int main(int argc, char *argv[]) { 

    printf("\n---Program---\n\n"); 

    char *word; 
    char add = 'x'; 

    item * item = malloc(sizeof(item)); 

    item->word = "this is a word"; 
    //printf("%s",item->word); 

    printf("\n\n"); 

    space(item,add); 

    return 0; 
} 

這裏是我得到的錯誤:

Seg故障!!!

回答

0

你是malloc ing結構的空間,但不是結構中的字符串。

item * item = malloc(sizeof(item)); 
item->word = malloc(sizeof(char) * MAXSTRINGSIZE); //add this line or something similar 
strcpy(item->word, "this is a word"); 
+0

所有這一切都是泄漏的分配。 sizeof(char)是1. –

+0

或者只是'item-> word = strdup(「這是一個單詞」);'並且保存一行。 –

+0

@CarlNorum假設你在POSIX系統上...... – Oka