程序如下,請指出錯誤代碼,謝謝。。
// a.h
#ifndef _A_H
#define _A_H
#define int32_t int
#define uint32_t unsigned int
#define TMax 1;
#define TMin -1;
#define NULL 0;
int32_t sat_add(int32_t, int32_t, int32_t*);
uint32_t sat_sub(uint32_t, uint32_t, uint32_t*);
#endif
//middle.c
#include "a.h"
uint32_t sat_add(uint32_t x, uint32_t y, uint32_t* flag)
{
uint32_t r = x + y;
if ( x > 0 && y > 0 && r < 0) //正溢出
{
*flag = TMax;
}
else if ( x < 0 && y < 0 && r > 0) //負溢出
{
*flag = TMin;
}
else //不溢出
{
*flag = NULL;
}
return r;
}
uint32_t sat_sub(uint32_t x, uint32_t y, uint32_t* flag)
{
uint32_t r = x - y;
if (x - r != x - (x - y)) {
*flag = TMin;
}
else {
*flag = NULL;
}
return r;
}
//main.c
#include<stdio.h>
#include "a.h"
void main() {
int32_t c = 0;
int32_t x1, y1,t1;
int32_t *p1 = NULL;
uint32_t x2, y2,t2;
uint32_t *p2 = NULL;
printf_s("1 判斷加法溢出\n");
printf_s("2 判斷減法溢出\n");
printf_s("3 退出\n");
printf_s("輸入你的命令:");
scanf_s("%d", &c);
while (1) {
switch (c) {
case 1:
printf_s("輸入兩個有符號數:");
scanf_s("%d %d", &x1, &y1);
t1=sat_add(x1,y1,p1);
printf_s("%d %d", t1,*p1);
break;
case 2:
printf_s("輸入兩個無符號數:");
scanf_s("%d %d", &x2, &y2);
t2=sat_sub(x2,y2,p2);
printf_s("%d %d", t2,*p2);
break;
case 3:
break;
default:
printf_s("沒有該指令,重新輸入:");
break;
}
if (c == 3) break;
}
}
p1、p2初始化為NULL,在加減函數裡如果溢出被賦值,這麼使用是錯誤的。
p1、p2沒有指向具體空間,數存哪裡?
可以這樣:
int32_t tp1;
p1=&tp1;
uint32_t tp2;
p2=&tp2;