此程序只需使用ASCII行文件,将其放入链接列表堆栈,然后将反转列表打印为相同ASCII格式的新文件.
我的结构代码:
typedef struct Node{
char *info[15];
struct Node *ptr;
};
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Errors:
strrev.c:14: warning: useless storage class specifier in empty declaration
strrev.c: In function ‘main’:
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
Run Code Online (Sandbox Code Playgroud)
/usr/include/string.h:128:注意:预期'char*restrict '但参数类型为'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;
}
Run Code Online (Sandbox Code Playgroud)
在结构中引用结构的正确方法:
struct Node {
char info[15];
struct Node *ptr;
};
Run Code Online (Sandbox Code Playgroud)
当你创建一个结构时,你必须打字struct Node才能使用它.如果你想避免它,你可以制作一个typedef
typedef struct Node {
char info[15];
struct Node *ptr;
} Node;
Run Code Online (Sandbox Code Playgroud)
那么你可以Node在定义变量时使用,就像这样
Node myNode;
Run Code Online (Sandbox Code Playgroud)
(但最好避免对struct和typedef使用相同的名称以避免混淆).
但请注意,struct Node在引用自身时仍需要在struct中编写,因为此时还没有创建typedef.