簡體   English   中英

指向字符串的指針數組-C

[英]Arrays of pointers to strings - 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線,並且每條重復的線都得到一個普通的XORred線。
 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)

一樣的

filetostrmalloc不太正確。 它應該是

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

您需要為終止的空字符分配空間,不需要強制返回,可以依靠sizeof(char)為1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM