【发布时间】:2016-02-14 15:45:01
【问题描述】:
我有一个程序,它有一个函数可以将一个 void * 返回到一个结构中,但我认为我在转换数据时忽略了一些东西。
此函数创建一个包含字符串和 int 的结构。字符串是从文件中读入的。
void * buildWord(FILE * fin)
{
void * ptr;
char buf[100];
Words * nw = (Words *)calloc(1, sizeof(Words));
fgets(buf, 100, fin);
strip(buf);
nw->word = (char *)calloc(1, (strlen(buf) + 1));
nw->length = strlen(buf);
strcpy(nw->word, buf);
ptr = &nw;
return ptr;
}
这是调用 this 并接受 void * 的函数。
Node * buildNode(FILE * in, void *(*buildData)(FILE * in) )
{
Node * nn = (Node *)calloc(1, sizeof(Node));
nn->data = (Words*)((*buildData)(in));
return nn;
}
这是Node的结构
struct node
{
void * data;
struct node * next;
};
typedef struct node Node;
我知道单词结构的创建很好,但是当我开始使用列表中的节点时,其中没有数据。我不确定为什么会这样。谢谢!
【问题讨论】:
-
ptr = &nw;应该是ptr = nw;(nw已经是一个指针) -
另外,请学习 Not 转换 malloc/calloc 等的返回值。
Words * nw = (Words *)calloc(1, sizeof(Words));应该是Words * nw = calloc(1, sizeof(Words));或者只是Words * nw = calloc(1, sizeof *nw);malloc/calloc仅返回而已比新创建的内存块的起始地址。它只是一个地址,而不是char地址或int地址——只是一个地址。 -
既然你把它标记为
C++,为什么不直接使用std::list<Words>呢? -
@DavidC.Rankin 如果 OP 将删除
C++标签,您的评论是有意义的。如果 OP 使用C++,则需要强制转换。如果 OP is 使用 C++,则放弃所有这些并使用std::list。 -
感谢您的建议,并对 c++ 标签感到抱歉。这确实在c中。我删除了标签。
标签: c linked-list function-pointers nodes void-pointers