对于这种情况:
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章节:
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.
在草案中,没有提到“integer”是(有符号的)int
或unsigned
。
那么两者都可以在所有平台上用于指针操作数?
最佳答案
在此上下文中,“具有整数类型的表达式”指的是 any 整数类型,例如signed
或 unsigned
char
, short
, int
, long
或 long long
以及实现定义的任何其他整数类型。
因此,您可以安全地将 int
或 unsigned int
类型的参数与指针一起使用,前提是生成的指针仍指向同一个对象或数组。
关于C: int 或 unsigned int 我用于指针增加的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65998877/