2013-01-10 185 views
0

我有一個問題,我真的無法理解。我是一個新手C程序員,我有一個程序,大致是這樣的:字符串指針的數組 - C

void filetostr(FILE *, char *s[]); 
void strtofile(char *s[], FILE *); 
void XORstr(char *, int); 
void XORtext(char *s[], int); 
void printext(char *s[]); 

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

    char *s[MAXLENGTH]; 
    char ln[MAXLENGTH]; 

    FILE *input, *xorred, *rexorred, *out; 

    input = fopen("input.txt", "r"); 
    filetostr(input, s); 
    fclose(input); 

    printext(s); 

    XORtext(s, KEY);   
} 

void filetostr(FILE *fp, char *s[]) { 
    char ln[MAXLENGTH]; 
    char *p; 
    int i = 0; 

    while (fgets(ln, MAXLINE, fp)) { 
     p = (char *) malloc(strlen(ln) * sizeof(char)); 
     strcpy(p, ln); 
     s[i++] = p; 
    } 
} 

void printext(char *s[]) { 
    while (*s) { 
     printf("%s", *s); 
     s++; 
    } 
} 

void XORstr(char *s, int key) { 
    int c; 
    while (c = *s) 
     *s++ = key^c; 
} 

void XORtext(char *txt[], int key) { 
    while (*txt) { 
     XORstr(*txt, key); 
     txt++; 
    } 
} 

而且我有兩個兩個問題:

  • 首先,當我建立指針數組爲字符串與filetostr,我得到它的工作,但在文本中間的兩行重複(有兩個引用他們在數組中,所以printext他們打印兩次)。這怎麼可能?是否有錯誤的malloc調用?第二,當我嘗試對我剛纔提到的線進行XOR運算時,它們只會得到XORred一次,所以我最終得到了一條XORRED線和一條用於每條重複線的正常線。
+0

另外,不要忘記檢查1)返回來自'malloc()'函數的值。 'if(p == NULL){/ * no memory */exit(1); }'和2)如果在's'數組中有足夠的空間來存儲'p';在[i ++] = p之前:':'if(i> = MAXLENGTH){/ * s中沒有空格來保存p * /}'這可能會導致應用程序崩潰。 – Jack

回答

3
p = (char *) malloc((strlen(ln) + 1) * sizeof(char)); 

,而不是

p = (char *) malloc(strlen(ln) * sizeof(char)); 

順便說一句,你可以改變

p = (char *) malloc((strlen(ln)+1) * sizeof(char)); 
strcpy(p, ln); 
s[i++] = p; 

通過

s[i++] = strdup(ln) 

這是同樣的

+2

但是不是'strdup()'POSIX? – Jack

+0

這種方式我在哪裏沿陣列移動?以前我用'i ++'做過......也許我必須在'strdup'函數後加's [i ++] = p;'' – whatyouhide

+0

對不起,我在我的答案中犯了一個錯誤,應該是[i ++] = strdup(ln)'。我會更新答案 – MOHAMED

1

malloc in filetostr不太對。它應該是

p = malloc(strlen(ln) + 1); 

您需要爲終止空字符分配空間,無需轉換返回,並可以依靠sizeof(char)爲1