有人可以告诉我为什么当我编译它时,C告诉我总和不能表示为int
吗?
我不知道如何调试这一。我认为我创建的结构很好,而且计数和功能也不错。因此,请帮助我找出代码中的错误。
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *my_list();
int sum_list_values(struct node *list);
int main(){
struct node *list = my_list();
int sum = sum_list_values(list);
printf("%d", sum);
return 0;
}
struct node *my_list(){
struct node *new = malloc(sizeof(struct node));
new->data = 1;
struct node *new1 = malloc(sizeof(struct node));
new->data = 3;
struct node *new2 = malloc(sizeof(struct node));
new->data = 3;
struct node *new3 = malloc(sizeof(struct node));
new->data = 7;
new->next = new1;
new1->next = new2;
new2->next = new3;
new3->next = NULL;
return new;
}
int sum_list_values(struct node *list){
struct node *current = list;
int sum = 0;
while(current != NULL){
printf("Hello");
sum = sum + current->data;//counter
current = current->next;//increment
}
return sum;
}
答案 0 :(得分:2)
您犯了一个不明显的小错误
代码部分
struct node *new1 = malloc(sizeof(struct node));
new->data = 3;
struct node *new2 = malloc(sizeof(struct node));
new->data = 3;
struct node *new3 = malloc(sizeof(struct node));
new->data = 7;
每次都将值分配给同一节点,新创建的节点将保留未分配的数据(不良节点)。
应改为
struct node *new1 = malloc(sizeof(struct node));
new1->data = 3;
struct node *new2 = malloc(sizeof(struct node));
new2->data = 3;
struct node *new3 = malloc(sizeof(struct node));
new3->data = 7;
希望这会有所帮助。
继续提问,保持成长:)