[我正在编写一些学校课程,我必须使用'void const * content'作为参数。我在打印新节点的内容时遇到问题。没有'const'的代码可以工作并显示正确的所有内容。有人可以指出我在做什么错吗?
终端输出: � 6
#include <stdio.h>
#include <stdlib.h>
typedef struct s_list
{
void *content;
size_t content_size;
struct s_list *next;
} t_list;
t_list *lstnew(void const *content, size_t content_size)
{
struct s_list *new = (struct s_list*)malloc(sizeof(struct s_list*));
if(new == NULL){
printf("No allocation!");
exit(1);
}
new->content = &content;
new->content_size = content_size;
new->next = NULL;
return(new);
}
int main(void)
{
printf("%s\n", lstnew("Hello", 6)->content);
printf("%zu\n", lstnew("Hello", 6)->content_size);
return(0);
}
您要在此处使用局部变量的地址:
new->content = &content;
相反,只需取值:
new->content = content;
此外,您在这里没有分配足够的内存;您只为指针分配了足够的空间,而不是结构的大小:
struct s_list *new = (struct s_list*)malloc(sizeof(struct s_list*));
malloc
上的强制转换也是不必要的。我会这样写:
struct s_list *new = malloc(sizeof(*new));
而不是使用typedef
,您应该只在各处使用struct s_list
,因为该结构并非旨在不透明。