2

这个程序简单地获取一个带有 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;
}
4

2 回答 2

5

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

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

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

于 2013-10-02T07:50:48.763 回答
2

你需要先有一个Nodetypedef

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

或者一次性完成

typedef struct Node{
    char *info[15];
    struct Node *ptr;
} Node;
于 2013-10-02T07:52:05.023 回答