我正在尝试将字符串动态添加到链接列表中。 (我不知道会有多少根弦)。
这是迄今为止我发现的代码:
struct node
{
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------
void creat()
{
char ch;
do
{
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
printf("nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
current->next=new_node;
current=new_node;
}
printf("nDo you want to creat another : ");
ch=getche();
}while(ch!='n');
}
//------------------------------------------------------------------
void display()
{
struct node *new_node;
printf("The Linked List : n");
new_node=start;
while(new_node!=NULL)
{
printf("%d--->",new_node->data);
new_node=new_node->next;
}
printf("NULL");
}
如果我想将字符串添加到链表结构中,我只需更改:
struct node {
int data;
至:
struct node {
char abc[256];
并将所有 %d 更改为 %s?就这么简单吗?
最佳答案
是啊!它也会起作用。但更好的方法是保留一个临时缓冲区来存储字符串输入。现在,每当您获得一个字符串时,只需动态分配(使用malloc()
)该数字字符+ 1 个字符到该指针。并使用 strcpy()
将缓冲的输入复制到其中。看看这个代码片段。
struct struct_name
{
char *data;
....
};
char buffer[MAXBUFFERSIZE];
scanf("%s",buffer);
struct struct_name * temp= (struct struct_name*) malloc(sizeof(char)*(strlen(buffer)+1));
if(temp==NULL)
{
//error.
}
strcpy(temp->data,buffer);
.....
关于c - 将字符串插入链表结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129393/