在 C 中使用带有取消引用的增量运算符
Using Increment operator with de-referencing in C
对于我的函数,我得到一个空指针,考虑到传入指针是 char 类型,我想指向下一个位置。
int doSomething( void * somePtr )
{
((char*)somePtr)++; // Gives Compilation error
}
我得到以下编译错误:
Error[Pe137]: expression must be a modifiable lvalue
这是运算符优先级的问题吗?
转换不产生左值(参见 C11 标准第 6.5.4 节脚注 104),因此您不能应用 post 增量 ++
运算符到它的结果。
In C, a cast operator does not mean "pretend these bits have a different type, and treat them accordingly"; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a deliberate but nonstandard extension if a particular compiler accepts expressions such as the above.)
试试这个
char *charPtr = ((char*)somePtr);
charPtr++;
如果你想将指针移动到下一个,你可以使用:
*ptr++;
如果你想将指针位置复制到另一个变量,那么:
char *abc = (char*)(def + 1);
这真的取决于你做事的动机
对于我的函数,我得到一个空指针,考虑到传入指针是 char 类型,我想指向下一个位置。
int doSomething( void * somePtr )
{
((char*)somePtr)++; // Gives Compilation error
}
我得到以下编译错误:
Error[Pe137]: expression must be a modifiable lvalue
这是运算符优先级的问题吗?
转换不产生左值(参见 C11 标准第 6.5.4 节脚注 104),因此您不能应用 post 增量 ++
运算符到它的结果。
In C, a cast operator does not mean "pretend these bits have a different type, and treat them accordingly"; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a deliberate but nonstandard extension if a particular compiler accepts expressions such as the above.)
试试这个
char *charPtr = ((char*)somePtr);
charPtr++;
如果你想将指针移动到下一个,你可以使用:
*ptr++;
如果你想将指针位置复制到另一个变量,那么:
char *abc = (char*)(def + 1);
这真的取决于你做事的动机