2017-08-01 52 views
-1

消息算術工作:爲什麼沒有在指針的char *功能

/usr/local/webide/runners/c_runner.sh: line 54: 20533 Segmentation fault 
nice -n 10 valgrind --leak-check=full --log-file="$valgrindout" "$exefile" 

我不明白爲什麼我不能使用指針運算時,我的功能類型不是void。看看這個例子:

假設我必須編寫一個函數,可以在字符串中的第一個單詞之前'擦除'所有空格。 例如,如果我們有一個字符數組:

" Hi everyone" 

它應該生產函數的修改後"Hi everyone"

這裏是我的代碼的時候,而不是 char* EraseWSbeforethefirstword()
void EraseWSbeforethefirstword工作正常。

當函數返回一個對象char*它甚至不能被編譯。

char* EraseWSbeforethefirstword(char *s) { 
    char *p = s, *q = s; 

    if (*p == ' ') { /*first let's see if I have a string that begins with a space */ 
     while (*p == ' ') { 
      p++; 
     } /*moving forward to the first non-space character*/ 

     while (*p!= '\0') { 
      *q = *p; 
      p++; 
      q++; 
     } /*copying the text*/ 

     *q = '\0'; /*If I had n spaces at the beginning the new string has n characters less */ 
    } 
    return s; 
} 
+0

究竟是什麼你想達到什麼樣的?哦,你可以請格式化你的代碼,這樣它可以更容易閱讀...... – ZeusInTexas

+0

你沒有在編譯的代碼中添加return語句嗎? –

+0

你的函數改變's'的位置。看起來你想讓它返回一些東西。你想讓它返回什麼?請向我們展示您的代碼,不編譯。 –

回答

2

這是一個函數實現,返回類型爲char *,如果您想要。

#include <stdio.h> 

char * EraseWSbeforethefirstword(char *s) 
{ 
    if (*s == ' ' || *s == '\t') 
    { 
     char *p = s, *q = s; 

     while (*p == ' ' || *p == '\t') ++p; 

     while ((*q++ = *p++)); 
    } 

    return s; 
} 

int main(void) 
{ 
    char s[] = "\t Hello World"; 

    printf("\"%s\"\n", s); 

    printf("\"%s\"\n", EraseWSbeforethefirstword(s)); 

    return 0; 
} 

程序輸出是

" Hello World" 
"Hello World" 

要考慮到你可能不修改字符串文字。因此,該程序將有不確定的行爲,如果而非陣列

char s[] = "\t Hello World"; 

會有被宣佈爲指針,如果你想要這個函數可以處理字符串字面量則該函數的字符串字面

char *s = "\t Hello World"; 

必須動態分配一個新數組並返回一個指向其第一個元素的指針。

如果您不能使用標準的C字符串函數,則函數可以看看下面的方式

#include <stdio.h> 
#include <stdlib.h> 

char * EraseWSbeforethefirstword(const char *s) 
{ 
    size_t blanks = 0; 

    while (s[blanks] == ' ' || s[blanks] == '\t') ++blanks; 

    size_t length = 0; 

    while (s[length + blanks] != '\0') ++length; 

    char *p = malloc(length + 1); 

    if (p != NULL) 
    { 
     size_t i = 0; 
     while ((p[i] = s[i + blanks]) != '\0') ++i; 
    } 

    return p; 
} 

int main(void) 
{ 
    char *s= "\t Hello World"; 

    printf("\"%s\"\n", s); 

    char *p = EraseWSbeforethefirstword(s); 

    if (p) printf("\"%s\"\n", p); 

    free(p); 

    return 0; 
} 
+0

它說問題是「* q ='\ 0';」當我刪除該命令,然後它說,問題是行「while(* p =='')」...我知道如何使代碼更接受estetically可以接受......它說問題是「while(* q ++ = * p ++)「如果我寫它而不是我的三四行代碼相同 – Djule

+0

@Djule正如你在我的函數實現中看到的那樣,使用了兩對括號。 –

+0

@Djule或者你可以寫,而((* q ++ = * p ++)!='\ 0'); –