我正在用C编写程序,我有一些我不理解的错误。
这是我的main
:
#include "res.h"
#include <stdio.h>
#include <conio.h>
int main(){
Kitchen List;
char *name = "Productname";
float price = 5.6, qwan = 4;
List.head = NULL;
CreateProduct(name, price, qwan, &List);
getch();
return 0;
}
这是我的头文件:
#include <stdio.h>
#ifndef _res
#define _res
typedef struct Portion{
char *pName;
float pPrice;
float pQuantity;
Portion *next;
}Portion;
typedef struct Kitchen{
Portion *head;
int size;
}Kitchen;
void get_lost(char *string);
/*
Name : get_lost
Output: Void
Algorithem:
*/
void CreateProduct(char *name, float price, float quantity, Kitchen *List);
/*
Name : CreateProduct
Output: Void
Algorithem:
*/
#endif
这是我的res.c
:
#include "res.h"
//Prints an error msg.
void get_lost(char *string){
printf("%s", string);
getch();
exit(1);
}
//Creates nodes of portion type.
void CreateProduct(char *name, float price, float quantity, Kitchen *List){
Portion *temp = List->head;
Portion *newPortion = (Portion*)malloc(sizeof(Portion)); //Allocating memory for new node.
if (newPortion == NULL)
get_lost("Memory allocation has failed!");
newPortion->pName = (char*)malloc(sizeof(char)*strlen(name) + 1); //Allocating memory for portion name.
if (newPortion == NULL)
get_lost("Memory allocation has failed!");
strcpy(newPortion->pName, name); //Copy name of product to pName.
newPortion->pPrice = price; //Initializing Portion price.
newPortion->pQuantity = quantity; //Initialzing Portion quantity.
while (List->head != NULL)
{ //We check if portion is already in the list.
if (strcmp(List->head->pName, newPortion->pName))
{
printf("This portion already exists.");
return;
}
List->head = List->head->next;
}
List->head = temp; //We saved the head of the list in a tempoaray variable.
newPortion->next = List->head; //Add newPortion to the list.
List->head = newPortion;
List->size++; //We count the number of portions in the list.
}
我收到以下错误,我不明白为什么:
Error 26 error C2143: syntax error : missing ')' before '*'
Error 27 error C2081: 'Kitchen' : name in formal parameter list illegal
Error 28 error C2143: syntax error : missing '{' before '*'
有人可以帮我找出问题所在吗?
答案 0 :(得分:2)
变化:
typedef struct Portion{
char *pName;
float pPrice;
float pQuantity;
Portion *next;
}Portion;
为:
typedef struct Portion{
char *pName;
float pPrice;
float pQuantity;
struct Portion *next; // <<<
}Portion;
另请注意you shouldn't cast the result of malloc in C,所以要改变,例如
Portion *newPortion = (Portion*)malloc(sizeof(Portion));
为:
Portion *newPortion = malloc(sizeof(Portion));
或者最好:
Portion *newPortion = malloc(sizeof *newPortion);
答案 1 :(得分:0)
你犯了一个常见的错误。 typedef struct Portion{ };
是一个自引用结构,因为它有*next
类型的指针struct Portion
因此,当您将结构声明为
typedef struct Portion{
char *pName;
float pPrice;
float pQuantity;
Portion *next;
}Portion;
编译器还不知道Portion
是什么类型。
所以你必须将其声明为,
typedef struct Portion{
char *pName;
float pPrice;
float pQuantity;
struct Portion *next;
}Portion;
我更愿意将其定义为Portion_t
而不是Portion
。对于typedef
和struct
来说,是否应该使用union
这是一个非常矛盾的问题,因为作为独立的开发者,我需要知道它是否是struct
或union
。