C: int 或 unsigned int 我用于指针增加的类型

标签 c pointers integer pointer-arithmetic

对于这种情况:

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”是(有符号的)intunsigned

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

最佳答案

在此上下文中,“具有整数类型的表达式”指的是 any 整数类型,例如signedunsigned char, short, int, longlong long 以及实现定义的任何其他整数类型。

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

关于C: int 或 unsigned int 我用于指针增加的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65998877/

相关文章:

c - C中的指针算术和 "generic"

java - 从字符串中检索整数

c++ - c++中带字符串的大数的阶乘

c - 记事本无法识别换行符 '\n',但可以与制表符等其他特殊字符配合使用

c - 如何将 <mhash.h> 添加到我的 C 项目中

c - 这段c代码中数组/指针的输出是什么

python - 模拟 python 类属性的类似指针的行为

将特定的字符数组范围转换为字符串

pointers - Go 语言中地址的按位异或

hibernate - java.sql.SQLException : Invalid value for getInt() - 'foo'