我有一個問題,我真的無法理解。我是一個新手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線和一條用於每條重複線的正常線。
另外,不要忘記檢查1)返回來自'malloc()'函數的值。 'if(p == NULL){/ * no memory */exit(1); }'和2)如果在's'數組中有足夠的空間來存儲'p';在[i ++] = p之前:':'if(i> = MAXLENGTH){/ * s中沒有空格來保存p * /}'這可能會導致應用程序崩潰。 – Jack