2014-10-09 181 views
-1

所以我知道編程的基礎,我有一個體面的數量與java的經驗,但即時學習C的學校現在。我仍然沒有完全理解整個指針方面,這是我確定導致錯誤的原因。這個程序在我的電腦上運行時工作正常,但是當我嘗試在我的學校unix shell上運行它時,它給我一個seg故障。如果有人可以請向我解釋爲什麼或如何濫用指針,這對我很有幫助。seg故障/指針幫助

//Matthew Gerton 
//CS 222 - 002 
//10/10/14 
//HW Six 

//libraries 
#include<stdio.h> 
#include<string.h> 
#define max_Length 256 

//prototypes 
void decode(char *a, char *b); 
void trimWhite(char *a); 
void encode(char *a, char *b); 

int main(void) 
{ 
    //character arrays 
    char coded[max_Length], decoded[max_Length]; 

    //decode the sample phrase 
    char sample[] = {'P','H','H','W','D','W','C','R','R','F','D','Q','F','H','O','H','G','J', 
       'R','W','R','P','H','W','U','R','K','R','W','H','O','U','R','R','P','I','R','X','U'}; 

    decode(sample, decoded); 

    //scans a user input string to decode, and decodes it 
    printf("\nPlease enter a phrase to decode: "); 
    gets(coded); 
    trimWhite(coded); 
    decode(coded, decoded); 

    //scans a user input phrase to encode 
    printf("\nPlease enter a phrase to encode: "); 
    gets(coded); 
    trimWhite(coded); 
    encode(coded, decoded); 
} 

//removes any spaces from the input 
void trimWhite(char *a) 
{ 
    char temp[max_Length]; 
    int z=0, y=0; 
    while(a[z]!='\0') 
    { 
     if(a[z]!=' ') 
     { 
      temp[y]=a[z]; 
      y++; 
     } 
     z++; 
    } 
    temp[y] = '\0'; 
    strcpy(a,temp); 
    } 

//decodes any phrase 
void decode(char *a, char *b) 
{ 
    int i=0,n; 
    memset(b, '\0', sizeof(b)); 
    while(a[i]!='\0') 
    { 
     n=(int)a[i]; 
     if(n<97) 
      n=n+32; 
     if(n<=99) 
      n=n+23; 
     else 
      n = n-3; 
     b[i]= (char) n; 
     i++; 
    } 
    b[i]='\0'; 
    printf("Coded message: %s\n", a); 
    printf("Decoded message: %s\n", b); 
} 
//codes an input phrase 
void encode(char *a, char *b) 
{ 
    int i=0,n; 
    memset(b, '\0', sizeof(b)); 
    strcpy(b,a); 
    while(a[i]!='\0') 
    { 
     n=(int)a[i]; 
     if(n<97) 
      a[i] = (char)(n+32); 
     if((n>120) 
      a[i] = (char)(n-23); 
     else 
      a[i] = (char)((n+3); 

     i++; 
    } 
    printf("Coded message: %s\n", a); 
} 

回答

0
  • 你的主要問題是在這裏:

    char sample[] = {'P','H','H', /* snip */ ,'R','X','U'}; 
    

    sample[]陣列不是零封端的並因此可能導致decode()功能來複制許多更多的字符比預期,從而覆蓋其他變量。你需要明確添加終結零使用初始化列表時:

    char sample[] = {'P','H','H', /* ... */ ,'R','X','U',0};

    或者你也可以使用一個字符串,其中包括初始化數組終止零:

    char sample[] = "PHHWDWCRRFDQFHOHGJRWRPHWURKRWHOURRPIRXU"; 
    
  • 您應該閱讀"Why is the gets function dangerous"

  • ...

    void decode(char *a, char *b) 
    { 
        int i=0,n; 
        memset(b, '\0', sizeof(b)); 
    

    還要注意,當它傳遞給函數的數組的大小都將丟失。該函數只收到一個指向其第一個元素的指針。上面的調用memset()只會爲零sizeof(char*)字節(通常爲4或8)。這並不重要,因爲,就我所知,只需要將第一個字節清零。你可以簡單地寫:

    b[0] = 0;