gpt4 book ai didi

C. 二进制 * 的无效操作数(有 ‘char *’ 和 ‘int’ )

转载 作者:行者123 更新时间:2023-11-30 20:09:25 25 4
gpt4 key购买 nike

嘿!我在C语言中学习#define。我的程序关于绝对值。我有 2 个文件:ft_abs.h:

#ifndef FT_ABS_H
# define FT_ABS_H

# define ABS(Value) ((Value < 0) ? (Value * (-1)) : (Value))

#endif

和main.c:

#include "ft_abs.h"
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
printf("%s", ABS(argv[1]));
return (0);
}

编译

gcc -o abs ft_abs.h main.c 

还有...

In file included from main.c:2:0: main.c: In function ‘main’: ft_abs.h:16:41: error: invalid operands to binary * (have ‘char *’ and ‘int’) # define ABS(Value) ((Value < 0) ? (Value * (-1)) : (Value)) main.c:17:18: note: in expansion of macro ‘ABS’ printf("%s", ABS(argv[1]));

当我将 (Value * (-1)) 更改为 (-Value) 时,它也不起作用(一元减号的类型参数错误)。如果我将 (-Value) 更改为 (Value) 一切都可以,但这是无意义的。我应该如何更改代码以使其工作(当然使用定义)?

最佳答案

argv[1] 的类型为 char *。计算绝对值没有任何意义。您可能希望将参数转换为 int 类型,然后计算绝对值。

printf("%d", ABS(strtol(argv[1], NULL, 10)));

此外,在编写宏时,您应该始终在参数两边加上括号。

#define ABS(Value) (((Value) < 0) ? ((Value) * (-1)) : (Value))

关于C. 二进制 * 的无效操作数(有 ‘char *’ 和 ‘int’ ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52583134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com