我正在用 C 语言编写程序,并且有一些我不明白的错误。
这是我的主要
:
#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 '*'
有人可以帮我找出问题所在吗?
最佳答案
更改:
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);
关于编译错误 "name in formal parameter list illegal",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30368262/