gpt4 book ai didi

c - 我如何找到一个微妙的错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:43 24 4
gpt4 key购买 nike

我不明白为什么变量的值为 0,它应该是 23?

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int array[] = {23, 34, 12, 17, 204, 99, 16};
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int main(){
int d = -1, x = 0;
if (d <= TOTAL_ELEMENTS - 2)
x = array[d + 1];
printf("x= %d \n", x);
return 0;
}

最佳答案

这是由于通常的算术转换

当运算符的操作数同时涉及有符号整数和无符号整数,并且无符号类型至少与有符号类型一样大时,有符号值将转换为无符号值。当带符号的值为负时,它会转换为一个大的正值。

整数转换的规则在 C standard 的第 6.3.1.8p1 节中有详细说明。 :

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Otherwise, both operands are converted to the unsigned
integer type corresponding to the type of the operand with signed integer type

在这个表达式中:

(d <= TOTAL_ELEMENTS - 2)

扩展为:

(d <= (sizeof(array) / sizeof(array[0])) - 2)

sizeof运算符的计算结果为 size_t 类型的值这是未签名的。所以操作数的类型看起来像这样:

(int <= ((size_t / size_t) - int)

/ 的两个操作数运算符的类型是 size_t所以该操作的结果是 size_t 类型.然后是-的右操作数转换为类型 size_t .由于值 2 适合该类型,因此该值不会改变。

现在我们有了 <=运算符 int一个尺寸和一个size_t在另一。左操作数由 int 转换而来至 size_t ,但是值 -1 不适合该类型,因此它被转换。转换后的值实际上是 size_t 的最大可能值因此大于右侧的值,结果为 <=错误。

要解决此问题,您需要将右侧的无符号值强制转换为有符号值,以防止转换左侧值:

if (d <= (int)(TOTAL_ELEMENTS - 2))

关于c - 我如何找到一个微妙的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089584/

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