2013-01-19 106 views
2
void convert(char *str){ 
    int i = 0; 
    while (str[i]){ 
    if (isupper(str[i])){ 
     tolower(str[i]); 
    } 
    else if (islower(str[i])){ 
     toupper(str[i]); 
    } 
    i++; 
    } 
    printf(str); 
} 

在該函數中,我試圖顛倒字符串中每個字母的大小寫。我打電話給這樣的功能:混淆傳遞字符串作爲C函數的參數

convert(input); 

其中input是一種char *。我得到了分段錯誤錯誤。這裏有什麼問題?

謝謝!

更新: 我的輸入取自argv [1]。

char *input; 
    if (argc !=2){/* argc should be 2 for correct execution */ 
    /* We print argv[0] assuming it is the program name */ 
    printf("Please provide the string for conversion \n"); 
    exit(-1); 
    } 
    input = argv[1]; 
+1

「輸入」的*值*是什麼?請注意,只是調用'tolower'實際上並沒有改變它的值 - 它*返回*小寫值...您需要將它寫回到char *'中。 –

+3

'input'是否以null結尾?分段錯誤可能是由於您試圖訪問分配區域之外的內存位置所致。另外,更換套管的更簡單方法是應用模數:'str [i] = str [i]%0x20;' –

+1

如何初始化'input'? –

回答

6

這不工作的原因是您要刪除的touppertolower結果。您需要分配結果回傳給插入函數的字符串:

if (isupper(str[i])){ 
    str[i] = tolower(str[i]); 
} else if (islower(str[i])){ 
    str[i] = toupper(str[i]); 
} 

注意,爲了使這項工作的str必須修改,這意味着呼叫convert("Hello, World!")將是不確定的行爲。

char str[] = "Hello, World!"; 
convert(str); 
printf("%s\n", str);