cstring 给初学者带来的麻烦
我正在尝试制作一个程序,逐行读取文件,然后将读取的行放入链接列表中,我的问题是将字符串添加到列表中。看看代码,在 else 测试中你可以看到我的问题。
#include<stdlib.h>
#include<stdio.h>
struct list_el {
char *ord;
struct list_el * next;
};
typedef struct list_el item;
int main(int argc, char *argv[]) {
int c;
item *curr, *head;
head = NULL;
FILE *fileHandle = fopen("tresmaa.txt", "r");
while((c = fgetc(fileHandle)) != '\n' || c != EOF)
if(c == EOF) {
printf("\n");
break;
} else {
curr = (item*)malloc(sizeof(item));
curr->ord = "I cant point curr -< ord = c, how can i point the readed sentences to the value Ord?";
curr->next = head;
head = curr;
putchar(c);
}
curr = head;
while(curr) {
printf("%s\n", curr->ord);
curr = curr->next ;
}
}
I'm trying to make a program that read a file line by line and then put the readed line into a a linked list, my problem is to add the string to list. Look at the code, in the else test you can see my problem.
#include<stdlib.h>
#include<stdio.h>
struct list_el {
char *ord;
struct list_el * next;
};
typedef struct list_el item;
int main(int argc, char *argv[]) {
int c;
item *curr, *head;
head = NULL;
FILE *fileHandle = fopen("tresmaa.txt", "r");
while((c = fgetc(fileHandle)) != '\n' || c != EOF)
if(c == EOF) {
printf("\n");
break;
} else {
curr = (item*)malloc(sizeof(item));
curr->ord = "I cant point curr -< ord = c, how can i point the readed sentences to the value Ord?";
curr->next = head;
head = curr;
putchar(c);
}
curr = head;
while(curr) {
printf("%s\n", curr->ord);
curr = curr->next ;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
相反,您需要分配一个缓冲区并将字符串放入其中,
例如
因为
只分配包含“ord”指针的结构,而不分配它所指向的内容。
另一件看起来有点可疑的事情是,
看起来更像是名称应该是“上一个”而不是“下一个”,
否则如果你想要一个“正常”的 FIFO 链表,只需有一个 head ptr 和一个end ptr,然后使用 end ptr 追加元素,同时保持头指向第一个列表元素。
instead you need to allocate a buffer and place the string in it
e.g.
because
only allocates the struct including the 'ord' pointer, but not what it points to.
another thing that looks a bit suspicious is
looks more like the name should have been 'prev' and not 'next' the way you do it (LIFO)
otherwise if you want a "normal" FIFO linked list just have a head ptr and an end ptr, then use the end ptr to append elements while keeping the head pointing to the first list element.
我在其他方面看到了你的问题。 :)
你的结构的 malloc 是不够的。这个malloc只创建struct memory(两个指针)的内存,而不创建内部的内存。您还必须使用适当大小的字符串来分配 char 内存 (
ord
)。使用strlen
并对 null 加一来确定该字符串的大小。I see your problem in the else. :)
Your malloc of the struct is not sufficient. This malloc only creates the memory of the struct memory (two pointers) not the memory inside. You'll have to malloc your char memory (
ord
) with the proper size of the string as well. Usestrlen
and add one for null to determine size of this string.是的!
is right!