2017-04-17 122 views
-3

當我嘗試編譯這個時,我總是收到分段錯誤。我是否需要檢查偶數和奇數?我知道這意味着我試圖獲得我沒有的記憶,但我不知道我犯了什麼錯誤。這也是C。保持分段錯誤(核心轉儲)

#include<stdio.h> 

int main() 
{ 
    char str[41], even[21], odd[21], *p, *pstr, *e, *o; 

    printf("Enter a string (40 characters maximum):"); 
    scanf("%s", str); 

    *p=str[0]; 
    *pstr=str[0]; 

    for(*p=even[0]; *p != '\0';p++){ 
     if((p-pstr) % 2 == 0){ 
      *e=*p; 
      e++; 
     } else{ 
      *o=*p; 
      o++; 
     } 
    } 

    *o = '\0'; 
    *e = '\0'; 

    printf("The even string is:%s", even); 
    printf("The odd string is:%s", odd);     

    return 0; 
} 
+2

'* p = str [0 ]。 * pstr = str [0];'使用未初始化的變量。 – BLUEPIXY

+2

當你這樣做時,你認爲'p'指向了什麼:'* p = str [0]'? – WhozCraig

回答

2

有關於指針在代碼中初始化一些困惑:

  • *p = str[0]副本從str的地址由p,這是未初始化指出的第一個字符,從而導致不確定的行爲。
  • 應的p的值,而不是初始化的str[0]地址:

    p = &str[0]; 
    

    可以簡化爲

    p = str; 
    

這裏是一個修正版本:

#include <stdio.h> 

int main(void) { 
    char str[41], even[21], odd[21], *p, *pstr, *e, *o; 

    printf("Enter a string (40 characters maximum):"); 
    if (scanf("%40s", str) == 1) { 
     e = even; 
     o = odd; 

     for (p = pstr = str; *p != '\0'; p++) { 
      if ((p - pstr) % 2 == 0) { 
       *e = *p; 
       e++; 
      } else { 
       *o = *p; 
       o++; 
      } 
     } 

     *o = '\0'; 
     *e = '\0'; 

     printf("The even string is: %s\n", even); 
     printf("The odd string is: %s\n", odd);     
    }  
    return 0; 
} 
+0

非常感謝,現在對我有意義:) – billnye852

1

p具有沒有分配的內存,你可以設置p = strstr[0]不可複製的字符到一個隨機的內存地址,因爲p從未被分配一些內存它指向的。