c - C 中队列中打印的坏字符

标签 c printing queue

我正在尝试打印一个结构中包含字符数组的队列。 我只是读取带有一些网址的文本文件,将其插入队列并尝试打印。前 4 行没问题,但随后它开始在几乎所有其他行中打印坏字符。我不知道发生了什么事。即使我直接从 fgets 打印 char 数组,它也会正确打印,并且队列也会正确打印,所以......我很困惑......

有什么想法吗?

相关代码如下:

结构:

typedef struct n_queue {
    char *web;
    struct n_queue *next;
} QUEUE_NODE, *P_QUEUE_NODE;

typedef struct k_queue {
    P_QUEUE_NODE head;
    P_QUEUE_NODE tail;
} kind_queue;

读取文件:

void readFile(kind_queue *q) {
    char data[9][150];
    FILE *f=fopen("list.txt", "r");
    if (f == NULL) perror("Web list couldn't be found.");
    int j =0;
    int i;

    while (fgets(data[j],150, f)!=NULL) {
            //If I uncomment the line below, both char array and char array in queue
            //are printed allright
        //printf("%s", data[j]);

            //Supress the new line char
        for (i=0;i<150;i++) {
            if (data[j][i] == '\n') {
                data[j][i]='\0';
                break;
            }
        }

        push_queue(q, data[j]);
        j++;
    }

    fclose(f);
}

推送代码:

void push_queue(kind_queue *q, char *web){
    P_QUEUE_NODE p;
    p = (P_QUEUE_NODE) malloc(sizeof(QUEUE_NODE));
    p->next = NULL;
    p->web = web;
    if (is_empty(q)) q->tail = q->head = p;
    else{
        q->tail->next= p;
        q->tail = p;
    }
}

主要功能:

int main () {

    kind_queue queue, *pt_queue_struct;
    pt_queue_struct = &queue;
    pt_queue_struct = init_queue(pt_queue_struct);
    readFile(&queue);

    print_queue(&queue);

    return(0);
}

最后是打印功能:

void print_queue(kind_queue *q) {
    P_QUEUE_NODE paux;
    int j=1;
    for (paux=q->head; paux != NULL; paux=paux->next) {
        printf("%d: %s\n", j, paux->web);
        j++;
    }
}

真实文本:

http://www.google.es
http://stackoverflow.com
http://www.facebook.com
http://akinator.com/cea
http://developer.android.com/map
http://tirsa.es/65/65.htm
http://www.ufo.es/
http://thisty.com/init/
http://damned-c.me/

输出:

1: http://www.google.es
2: http://stackoverflow.com
3: http://www.facebook.com
4: http://akinator.com/cea
5: 
6: 
7: http://www.ufo.es/
8: http:/(dU[~
9: (dU[~

最佳答案

读入的数据存储在局部变量data中,当readFile退出时,该变量将超出范围。只要将数据复制到节点结构中就可以了。目前节点数据指针仅指向局部变量存储。

关于c - C 中队列中打印的坏字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15449316/

相关文章:

c - Linux | C 中的 Shell 实现 |重定向文件包括提示

windows - Windows 中的虚拟打印机,从哪里开始?

javascript - 动态创建的动画结束回调

python - 从优先级队列中删除任意项

c - postfix 计算器遇到段错误问题

c - 将数组的元素添加为 a[0],a[1]+a[2],a[3]+a[4]+a[5],a[6]+a[7]+a[8] +a[9]...等等

c - Strcpy:表现得更像 'strcut'

javascript - 单击时在新窗口中打印图像的最简单方法是什么?

python - pyqt打印预览QTableView

Java队列内存大小限制