c - void * 算术

标签 c auto-increment

#include<stdio.h>
int main(int argc,char *argv[])
{
   int i=10;
   void *k;
   k=&i;

   k++;
   printf("%p\n%p\n",&i,k);
   return 0;
}

++ 是对 void* 的合法操作吗?有些书说不是 但是 K & R 没有说任何关于 void * 算术的事情(K &R 2/e 的第 93,103,120,199 页)

请澄清。

PS:GCC 至少在 k++ 中没有提示。

最佳答案

这是一个GCC extension .

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

如果您添加 -pedantic 标志,它将产生警告:

warning: wrong type argument to increment

如果您想遵守标准,请将指针转换为 char*:

k = 1 + (char*)k;

标准规定不能对 void* 执行加法 (k+1),因为:

  1. 指针运算是通过将 k 视为指向 void 数组的第一个元素 (#0) 的指针来完成的 (C99 §6.5.6/7),k+1 将返回此“数组”中的元素 #1 (§6.5.6/8)。

  2. 为了使这个有意义,我们需要考虑一个 void 数组。 void 的相关信息是 (§6.2.5/19)

    The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

  3. 但是,数组的定义要求元素类型不能不完整(§6.2.5/20,脚注36)

    Since object types do not include incomplete types, an array of incomplete type cannot be constructed.

因此 k+1 不能是一个有效的表达式。

关于c - void * 算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3922958/

相关文章:

SQLite 仅插入主键

sqlite - 更改行ID而不破坏自动递增sqlite

mysql - 在 MySQL 中创建第二个 PK 作为 AI

检查c中的回文字符串

c - 两个不同程序中数据类型的复杂性有何区别?

c++ - 通过位域访问 char 中的位

php - 在 mysql 中创建一个更长的唯一自动增量列,第一行有 6 个字符

php - codeigniter 自动递增外键

c - Visual Studio : Unresolved external symbols after adding new DLL APIs

c - 程序返回字符而不是字符串