我正在尝试编辑这个程序。现在用户输入符号,我想让它与字符串一起工作。
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node *next;
};
struct queue
{
struct Node *top;
struct Node *bottom;
}*q;
void Write(char x)
{
struct Node *ptr=malloc(sizeof(struct Node));
ptr->data=x;
ptr->next=NULL;
if (q->top==NULL && q->bottom==NULL)
{
q->top=q->bottom=ptr;
}
else
{
q->top->next=ptr;
q->top=ptr;
}
}
char Read ()
{
if(q->bottom==NULL)
{
printf("Empty QUEUE!");
return 0;
}
struct Node *ptr=malloc(sizeof(struct Node));
ptr=q->bottom;
if(q->top==q->bottom)
{
q->top=NULL;
}
q->bottom=q->bottom->next;
char x=ptr->data;
free(ptr);
return x;
}
int main()
{
q= malloc(sizeof(struct queue));
q->top=q->bottom=NULL;
char ch='a';
printf("NOTE: To stop the entry, please enter 'q'!nn Enter a String: n");
while(ch!='q')
{
scanf("%c",&ch);
Write(ch);
}
printf("nThe entered String:nn");
while(q->bottom!=NULL)
{
ch=Read();
printf("%c",ch);
}
printf("nn");
system("PAUSE");
return 0;
}
所以我像这样编辑它(下面的代码),我得到错误"[error]不兼容的类型,当从类型'char*'分配到类型'char[10]'时"
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data[10];
struct Node *next;
};
struct queue
{
struct Node *top;
struct Node *bottom;
}*q;
void Write(char x[10])
{
struct Node *ptr=malloc(sizeof(struct Node));
ptr->data=x;
ptr->next=NULL;
if (q->top==NULL && q->bottom==NULL)
{
q->top=q->bottom=ptr;
}
else
{
q->top->next=ptr;
q->top=ptr;
}
}
char Read ()
{
if(q->bottom==NULL)
{
printf("Empty QUEUE!");
return 0;
}
struct Node *ptr=malloc(sizeof(struct Node));
ptr=q->bottom;
if(q->top==q->bottom)
{
q->top=NULL;
}
q->bottom=q->bottom->next;
char x=ptr->data;
free(ptr);
return x;
}
int main()
{
q= malloc(sizeof(struct queue));
q->top=q->bottom=NULL;
char ch][10]='a';
printf("NOTE: To stop the entry, please enter 'q'!nn Enter a String: n");
while(ch!='q')
{
scanf("%c",&ch);
Write(ch);
}
printf("nThe entered String:nn");
while(q->bottom!=NULL)
{
ch=Read();
printf("%c",ch);
}
printf("nn");
system("PAUSE");
return 0;
}
我不能解决这个问题,所以我很想得到一些帮助。。。
不能分配给数组,但可以将复制到它。
要复制字符串,请使用strcpy
:
strcpy(ptr->data, x);
或者,由于您的阵列有限,可以使用strncpy
:
strncpy(ptr->data, x, sizeof(ptr->data) - 1);
ptr->data[sizeof(ptr->data) - 1] = ' ';
对于strncpy
,如果源等于或长于指定长度,则不会添加终止的' '
字符,因此我们必须确保字符串正确终止。