【发布时间】:2018-11-05 02:41:36
【问题描述】:
我试图在每个节点中插入两个随机字符串,但是当我打印列表时,输出不正确。会是什么?我不擅长内存分配,所以如果有什么问题请解释我。我还尝试查看一个字符串是否覆盖了另一个字符串,但似乎并非如此。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
int times;
char name[100];
char number[100];
struct node* next;
};
typedef struct node* node;
void mklist(node* n){
*n=(node)malloc(sizeof(node*));
(*n)->times=0;
strcpy((*n)->name,"null");
strcpy((*n)->number,"null");
(*n)->next=(node)NULL;
}
void listins_beg(node* n,char name[],char num[],int tim){
node a;
a=(node)malloc(sizeof(node));
if(a==NULL) exit(1);
a->times=tim;
strcpy(a->number,num);
strcpy(a->name,name);
a->next=(node)(*n);
(*n)=a;
}
void printlist(node n){
node x;
x=n;
if(x->next==NULL) printf("EMPTY LIST");
else{
do{
printf("%s - %s\n",x->name,x->number);
x=x->next;
}while(x->next!=NULL);
}
}
void freelist(node* n){
node x;
for(;x->next!=NULL;(*n)=(*n)->next){
x=(*n);
free(x);
}
}
int main(void){
node n;
mklist(&n);
listins_beg(&n,"Hermanouhuhuuteu","4523-2248",300);
listins_beg(&n,"Luhu","4523-4887",299);
listins_beg(&n,"Lulamolute","4523-4687",512);
printlist(n);
freelist(&n);
return 0;
}
【问题讨论】:
-
typedef struct node* node;不,拜托,只是不。这会可怕地混淆你的代码。最好不要typedef指针,这样语义立即可见。但这只是自找麻烦。 -
我尝试使用
typedef struct node node,但它给了我很多错误和头痛:/ -
使用更多不同的标识符,然后重试。
-
在初学者甚至中级程序员水平上,很难将指针缠绕在指针上。不要通过隐藏涉及指针的事实来使其变得更加困难。很自然地假设
X是非指针类型,X*是指针(对于任何X)。如果没有*s 的帮助,您必须考虑什么是指针,什么不是指针,这让您自己变得更加困难。
标签: c list struct linked-list dynamic-allocation