0

本当に理解できない問題があります。私は初心者の 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++;
    }
}

そして、私には2つの問題があります:

  • まず、文字列へのポインターの配列を で作成するとfiletostr、機能しますが、テキストの途中で 2 行が繰り返されます (配列にはそれらへの参照が 2 つあるため、printext2 回出力されます)。そんなことがあるものか?malloc の呼び出しが間違っていませんか?
  • 次に、先ほど述べた行を XOR しようとすると、XORred が 1 回しか得られないため、重複行ごとに XORred 行と通常の行が作成されます。
4

2 に答える 2

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)

それは同じだ

于 2013-01-10T15:43:11.517 に答える
1

インは完全mallocfiletostr正しくありません。そのはず

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

sizeof(char)終了するヌル文字にスペースを割り当てる必要があります。リターンをキャストする必要はなく、 1であることに依存できます。

于 2013-01-10T15:43:45.463 に答える