读书人

请帮看一下这个小链表错在哪儿

发布时间: 2013-08-11 22:22:29 作者: rapoo

请帮看一下这个小链表错在哪里?
这个链表我只输入了一个成员,但是输出时有问题。

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "stdbool.h"
#include "stdlib.h"

#define SIZE 40

struct film
{
char title[SIZE];
int rating;
};

typedef struct film Item;

typedef struct node
{
Item item;
struct node * next;
}Node;

int main(void)
{
Node *current;
Item item;

puts("Enter first movie");
gets(item.title);
puts("Enter the rating <0-10>:");
scanf("%d", &item.title);
while(getchar() != '\n')
{
continue;
}

current = (Node *)malloc(sizeof(Node));
current->item = item;
current->next = NULL;
printf("%s %d\n", current->item.title, current->item.rating);

return 0;
}


黑窗口中得到的结果是

Enter first movie
qw
Enter the rating <0-10>:
12
-858993460
Press any key to continue

[解决办法]
1. scanf("%d", &item.title);这个地方错了 应该是scanf("%d", &item.rating);
2.current->item = item; 结构体不能直接赋值,不是基本类型。
[解决办法]

int main(void)
{
Node *current;
Item item;

puts("Enter first movie");
gets(item.title);
puts("Enter the rating <0-10>:");
// scanf("%d", &item.title);
// scanf("%d", item.title);//字符串, 本身就是首地址,
scanf("%d", &item.rating);//看需求这你是要rating;
while(getchar() != '\n')
{
continue;
}



current = (Node *)malloc(sizeof(Node));
// current->item = item; //这个结构你没有重载= 不能直接用
memcpy(current->item, item, sizeof(Item));//用这个函数拷贝buf
current->next = NULL;
printf("%s %d\n", current->item.title, current->item.rating);

return 0;
}


[解决办法]
楼上正解,改法如下:
1. scanf("%d", &item.title); -> scanf("%d", &item.rating);
2. current->item = item; -> memcpy(&current->item, &item, sizeof(Item));

[解决办法]
引用:
1. scanf("%d", &item.title);这个地方错了 应该是scanf("%d", &item.rating);
2.current->item = item; 结构体不能直接赋值,不是基本类型。

忽略第二条。
[解决办法]
bug:

current->item = item;

说明:结构体不能直接复制,如何成员变量存在字符串,更不能直接复制;
修改意见:
1.采用c++思想,针对自己的结构体重载复制运算符
2.结构体逐个成员赋值。
3.字符串复制采用memcpy函数

读书人网 >C语言

热点推荐