不知道为什么出这样的错,毫无头绪
//稀疏多项式
#include<stdio.h>
#include<stdlib.h>
typedef struct Ele { //定义多项式
float coef; //系数
int expn; //指数
}ele;
typedef struct Node { //定义结点
ele* data;
struct node* next; //指针域
}node;
node* head; //头指针
void Insert(int num, float a, int n) { //插入元素,这里是ax^n的形式
node* temp1 = head;
node* temp = (node*)malloc(sizeof(node));
if (temp == NULL) {
printf("Error");
exit(-1);
}
temp->data->coef = a;
temp->data->expn = n;
if (n <= 0) {
printf("Error");
exit(-1);
}
if (num == 1) {
temp->next = head;
head = temp;
}
else {
for (int i = 0; i < num - 2; i++) {
temp = temp->next;
}
temp1->next = temp->next;
temp->next = temp1;
}
}
void Print() {
node* temp = head;
printf("多项式为:");
while (temp != NULL) {
printf("%fx^%d", temp->data->coef, temp->data->expn);
temp = temp->next;
}
printf("\n");
}
void Plus() {
}
int main() {
head = NULL;
Insert(1, 1, 1);
Print();
}
报错的截图是这样的
//稀疏多项式
#include<stdio.h>
#include<stdlib.h>
typedef struct Ele { //定义多项式
float coef; //系数
int expn; //指数
}ele;
typedef struct Node { //定义结点
ele data;
Node* next; //指针域
}node;
node* head; //头指针
void Insert(int num, float a, int n) { //插入元素,这里是ax^n的形式
node* temp1 = head;
node* temp = (node*)malloc(sizeof(node));
if (temp == NULL) {
printf("Error");
exit(-1);
}
temp->data.coef = a;
temp->data.expn = n;
if (n <= 0) {
printf("Error");
exit(-1);
}
if (num == 1) {
temp->next = head;
head = temp;
}
else {
for (int i = 0; i < num - 2; i++) {
temp = temp->next;
}
temp1->next = temp->next;
temp->next = temp1;
}
}
void Print() {
node* temp = head;
printf("多项式为:");
while (temp != NULL) {
printf("%gx^%d", temp->data.coef, temp->data.expn);
temp = temp->next;
}
printf("\n");
}
void Plus() {
}
int main() {
head = NULL;
Insert(1, 1, 1);
Print();
return 0;
}
很简单啊,你这个data只是个指针,并没有分配空间啊
建议不用指针,直接ele data即可