[英]Dereference syntax when accessing a struct element in C
The code demo below works but I'm not sure it's syntactically correct.下面的代码演示有效,但我不确定它在语法上是否正确。
For example, should this例如,如果这
X = *((QWORD*)(pRegCtx->X));
be replaced with被替换为
X = *(QWORD*)(pRegCtx->X);
Plus code looks odd using a QWORD cast使用 QWORD 强制转换的 Plus 代码看起来很奇怪
RegisterContext RegCtx = { (QWORD)&X };
Without the (QWORD) cast, the linux c compiler reports:没有 (QWORD) 转换,linux c 编译器报告:
warning: initialization of 'long unsigned int' from 'QWORD *' {aka 'long unsigned int *'} makes integer from pointer without a cast [-Wint-conversion]
警告:从 'QWORD *' {aka 'long unsigned int *'} 初始化 'long unsigned int' 使得 integer 从没有强制转换的指针 [-Wint-conversion]
Any tips on how make it conform better to the C89 standard?关于如何使其更好地符合 C89 标准的任何提示?
https://www.onlinegdb.com/0pBta5XO2 https://www.onlinegdb.com/0pBta5XO2
#include <stdio.h>
#include <stdint.h>
typedef uint64_t QWORD;
typedef uint32_t DWORD;
typedef uint16_t WORD;
typedef uint8_t BYTE;
typedef struct RegisterContext
{
QWORD X;
} RegisterContext, *PREGISTERCONTEXT;
void MyFun(PREGISTERCONTEXT pRegCtx)
{
QWORD X = 0;
X = *((QWORD*)(pRegCtx->X));
X += 42;
*((QWORD*)(pRegCtx->X)) = X;
}
int main(void)
{
QWORD X = 0;
RegisterContext RegCtx = { (QWORD)&X };
MyFun(&RegCtx);
// Answer to the Ultimate Question of Life, the Universe, and Everything
printf("X=%lu\n",X);
return 0;
}
typedef struct RegisterContext
{
uint64_t X;
} RegisterContext;
void MyFun(RegisterContext *pRegCtx)
{
uint64_t X = 0;
X = pRegCtx->X;
X += 42;
pRegCtx->X = X;
}
int main(void)
{
uint64_t X = 0;
RegisterContext RegCtx = { X };
MyFun(&RegCtx);
X = RegCtx.X;
printf("X=%"PRIu64"\n", RegCtx.X);
return 0;
}
https://godbolt.org/z/noPW46W3r https://godbolt.org/z/noPW46W3r
If your structure represents the layout of the hardware register mapped into the address space then you need to use macros.如果您的结构代表映射到地址空间的硬件寄存器的布局,那么您需要使用宏。
typedef struct RegisterContext
{
uint64_t X;
uint64_t Y;
uint64_t Z;
uint64_t W;
} RegisterContext;
#define REG1ADDRESS 0x40000340
#define REG1 ((volatile RegisterContext*)REG1ADDRESS)
void setX(void)
{
REG1 -> Z = 0x45654564;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.