c - 链接列表和指针语法错误

标签 c pointers syntax struct

这个程序简单地获取一个带有 ASCII 行的文件,将其放入一个链表堆栈,然后以相同的 ASCII 格式将反向列表打印到一个新文件中。

我的结构代码:

typedef struct Node{
    char info[15];
    struct Node *ptr;
};

我在 Main 上遇到以下错误。大多数必须在我声明新节点头的地方做...该语法有什么问题?:

Errors
    strrev.c:28: error: ‘Node’ undeclared (first use in this function)
    strrev.c:28: error: (Each undeclared identifier is reported only once
    strrev.c:28: error: for each function it appears in.)
    strrev.c:28: error: ‘head’ undeclared (first use in this function)
    strrev.c:34: warning: passing argument 1 of ‘strcpy’ from incompatible pointer type
   /usr/include/string.h:128: note: expected ‘char * __restrict__’ but argument is of         type ‘char **’

主要代码:

int main(int argc, char *argv[])
{
    if (argc != 3) {
        fprintf(stderr, "usage: intrev <input file> <output file>\n");
        exit(1);
    }

    FILE *fp = fopen(argv[1], "r");
    assert(fp != NULL);


    Node *head = malloc(sizeof(Node));
    head->ptr=NULL;

    char str[15];
    while (fgets(str, 15, fp) != NULL){
        struct Node *currNode = malloc(sizeof(Node));
        strcpy(currNode->info, str);
        currNode->ptr = head;
        head=currNode;
    }

    char *outfile = argv[2];
    FILE *outfilestr = fopen(outfile, "w");
    assert(fp != NULL);

    while (head->ptr != NULL){
        fprintf(outfilestr, "%s\n", head->info);
        head = head->ptr;
    }

    fclose(fp);
    fclose(outfilestr);
    return 0;
}

最佳答案

结构的 typedef 语法错误。您需要将 typedef 名称​​放在结构定义之后:

typedef struct Node  /* <- structure name */
{
    /* ... */
} Node;  /* <- typedef name */

并且可以为结构和类型使用相同的名称,因为它们位于不同的命名空间中。

关于c - 链接列表和指针语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19132185/

相关文章:

c - 制作链表时出现Segmentation fault (core dumped)错误

c++ - this 指针从虚成员函数传递给模板

将字符串转换为字符指针数组

haskell - 无法将预期类型 'MultTree b' 与 '[MultTree b]' 匹配

c - printf 打印到 c 中的二进制文件

C TCP Server 关闭前不发送数据

c - 从列表中搜索缓冲区以查找任何字符串的高效算法

c++ - C++ 函数定义中的 "Type&"与 "Type*"

ruby - Ruby 中不同的括号是什么意思?

java - 解析数学表达式给出错误的树