【发布时间】:2014-01-08 13:29:39
【问题描述】:
我正在使用 sprintf 将 int 转换为字符串。然后我将字符串传递给函数 "enqueue" 。此函数接受字符串并将其插入到 FIFO 链表中。问题是,当我使用显式字符串调用enqueue() 时,它可以完美运行,但是当我使用sprintf 字符串缓冲区调用它时,它会以某种方式覆盖队列中已经存在的元素。
typedef struct
{
char *movie;
char *pkt;
} packet ;
struct node
{
packet page;
struct node *next;
} *front= NULL, *rear=NULL;
void display_fifo(){
struct node *t;
t=front;
while ((front==NULL)|| (rear==NULL))
{
printf("\nempty fifo\n");
return ;
}
while (t!=NULL)
{
printf("->%s\t %s\n", t->page.movie, t->page.pkt);
t= t-> next;
}
}
void enqueue(char * movie, char *pkt)
{
packet new;
new.movie= movie;
new.pkt=pkt;
struct node *p;
p= (struct node*)malloc(sizeof(struct node));
p->page= new;
p->next= NULL;
if (rear== NULL|| front ==NULL)
front=p;
else
rear->next=p;
rear=p;
}
void main(){
char buff[10];
int i;
for (i=1;i<=5;i++){
sprintf(buff, "%d", i);
enqueue("1", buff);
printf("***\n");
display_fifo();
}
}
上面写的代码我得到的输出:
*** ->1 1 *** ->1 2 ->1 2 *** ->1 3 ->1 3 ->1 3 *** ->1 4 ->1 4 ->1 4 ->1 4 *** ->1 5 ->1 5 ->1 5 ->1 5 ->1 5sprintf 是否有替代方法返回我应该使用的字符指针,或者我的enqueue() 有问题?
【问题讨论】:
标签: c string linked-list