3

对于这种情况:

int arr[] = {0, 1, 2};
void func (int* arr_in){
  int offset_0 = 0;
  int offset_1 = 1;
  int offset_2 = 2;
  printf("%d\n", *(arr_in + offset_0) );
  printf("%d\n", *(arr_in + offset_1) );
  printf("%d\n", *(arr_in + offset_2) );
}

int无论我使用的是还是,编译器都不会抱怨unsigned

其中两个结果似乎也是正确的。

$ clang test.c -Wall -o test

我参考了 C11 草案中的第 6.5.6/8 章:

当一个整数类型的表达式被添加到指针或从指针中减去时,结果具有指针操作数的类型。

在草案中,没有提到签名)intunsigned.

那么两者都可以用于所有平台上的指针操作数吗?

4

3 回答 3

5

在此上下文中,“具有整数类型的表达式”指的是任何整数类型,例如signedor unsigned charshortintlonglong long,以及由实现定义的任何其他整数类型。

因此,您可以安全地使用类型参数intunsigned int指针,前提是生成的指针仍指向同一个对象或数组。

于 2021-02-01T19:28:49.347 回答
1

int = 1unsigned int = 1是同一件事,int = -1ungisned int = -1不是同一件事。如果您使用 1、2 和 3,答案是肯定的,您可以“调用”它intunsigned int或任何您想要的。如果您希望偏移量为负数,例如您不能使用unsigned int,或者如果您希望偏移量更大2^31,那么您不能使用unsigned int.

于 2021-02-01T19:32:34.547 回答
1

Just read the C Standard carefully.

From the C Standard (6.2.5 Types)

17 The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types. The integer and real floating types are collectively called real types.

and now you can reread your quote from the C Standard

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.

So you may use even the type char that is neither signed or unsigned integer type.

于 2021-02-01T19:40:36.740 回答