创建函数修改为:loand* Createlist2(loand *l,int n)
{
...........
return l;
}
主函数中调用:
int main()
{
loand* l;
l = Createlist2(l, c);
.........
}
修改如下,供参考:
#include <stdio.h>
#include <malloc.h>
typedef struct loand {
int data;
struct loand* next;
}Loand;
Loand * Createlist2(Loand * l, int n)
{
l = (Loand*)malloc(sizeof(loand));
l->next = NULL;
Loand* r = l;
for (int i = 0; i < n; i++)
{
Loand* s = (Loand*)malloc(sizeof(Loand));
s->next = NULL;
printf("请输入一个数:");
scanf("%d", &s->data);
r->next = s;
r = s;
}
return l;
}
int main()
{
loand* l;
int c = 5, d;
l = Createlist2(l, c);
Loand* p = l->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
return 0;
}
这里的知识点是: 函数传参,拷贝传参。(你可以百度了解)
如果你要在函数内部申请内存或者改变变量,通过参数的方式使用,要么使用楼上说的返回值赋值的方式,要么参考我的传地址,而不是传值(拷贝了)
struct Data {
int val;
struct Data* next;
};
void createdata(struct Data* list, int n)
{
list = (struct Data*)malloc(sizeof(struct Data*));
if (list == NULL)
{
printf("error malloc \n");
return;
}
list->next = NULL;
list->val = 1;
}
void createdata1(struct Data** list, int n)
{
*list = (struct Data*)malloc(sizeof(struct Data*));
if (*list == NULL)
{
printf("error malloc \n");
return;
}
(*list)->next = NULL;
(*list)->val = 1;
}
int main(void)
{
struct Data* list = NULL;
createdata(list, 1);
if (list != NULL)
{
printf("%d \n", list->val);
}
else
{
printf("list is null \n");
}
createdata1(&list, 1);
if (list != NULL)
{
printf("%d \n", list->val);
}
else
{
printf("list is null \n");
}
return 0;
}