【发布时间】:2018-09-10 21:14:00
【问题描述】:
代码的一般描述:-
这是一个简单的 C 语言程序,使用结构来获取输入 用户并打印输出。输入和输出都定义为 单独文件中的单独功能。其他用户定义的错误 为检查 C 错误的错误处理创建头文件 函数调用,在这种情况下为“malloc”。环境:Linux,操作系统:fedora
错误
input.c:在函数“输入”中: input.c:17:8:错误:“错误”的参数 1 的类型不兼容 错误(*val,-1,“malloc”); //因为这一行而出错 //使用错误(int return_variable, value, "func_name") ^ 在 input.c:3:0 中包含的文件中: error.h:7:6:注意:预期为“int”,但参数的类型为“struct Eq” 无效错误(int val,int ret,char* func_name) ^~~~~ make: *** [Makefile:10: input.o] 错误 1main.c
//********* headers **********//
#include<stdio.h>
#include<stdlib.h>
//********** structure *********//
struct Eq
{
int *x;
int *y;
};
//********** Function prototypes ***********//
struct Eq* input();
int output(struct Eq*);
//*********** Main function *************//
int main()
{
struct Eq* num;
num = input(); //takes user input, returns to num
output(num); //prints the output, num passed as arg.
return 0;
}
input.c输入函数
#include<stdio.h>
#include<stdlib.h>
#include"error.h" //user defined header file
//********** structure *********//
struct Eq
{
int *x;
int *y;
};
struct Eq* input()
{
struct Eq *val;
val = (struct Eq*)malloc(sizeof(struct Eq));
error(*val, -1, "malloc"); //error because of this line //usage error(int return_variable, value, "func_name")
val->x = (int*)malloc(sizeof(int));
// *val->x = -1; //!! try changing this and func below to invoke error function !!
error(*val->x, -1, "malloc"); //no errors because of this
val->y = (int*)malloc(sizeof(int));
error(*val->y, -1, "malloc"); //no errors because of this
printf("Enter the value of x:");
scanf("%d", val->x);
printf("Enter the value of y:");
scanf("%d", val->y);
return val;
}
输出.c
#include<stdio.h>
#include<stdlib.h>
//********** structure *********//
struct Eq
{
int *x;
int *y;
};
int output(struct Eq *num)
{
printf("value of x=%d\n",*num->x);
printf("value of y=%d\n",*num->y);
return 0;
}
error.h错误处理程序头文件
#include<stdio.h>
#include<stdlib.h>
void error(int, int, char*);
void error(int val, int ret, char* func_name)
{
if(val == ret)
{
switch(ret)
{
case 0:
printf("fatal error at %s, return 0\n", func_name);
exit(1);
case -1:
printf("fatal error at %s, return -1\n", func_name);
exit(1);
}
}
return 0;
}
【问题讨论】:
-
你能用编译器产生的错误的确切文本更新你的问题吗?
-
malloc 在失败时返回一个空指针,并且为了检查错误,您首先取消引用它?
-
根据您的评论,
error的第一个参数也是int,而不是struct Eq -
感谢您的更新,但本网站不接受文字图片。请将图片替换为错误文本。
-
是的,参数不是结构,所以可以对错误处理程序进行哪些更改,以便可以传递结构。