c - 如何将结构视为内存位置并使用指针分别访问元素

标签 c pointers structure ansi

我有一个结构

typedef struct
{
    unsigned char status;
    unsigned char group_id;
    unsigned char acc_trip_level;
    unsigned char role[50];
    unsigned char standard_panic_header[50];
    unsigned char high_threat_message[50];
    unsigned char high_threat_header[50];
}cfg;

cfg test_val;

我将此结构作为参数传递给函数以及如何通过内存位置获取/访问结构的元素(换句话说,我想通过内存地址处理此结构)

void foo(cfg *ptr)
{
    printf("%zu\n", sizeof(*ptr)); //Gives size of the strcture
    printf("%p\n", (void*)ptr); //Gives the starting address of strcure
    printf("%p\n", (void*)(ptr+4));  //I want to access the 4th element/ memorylocation
}

正在给我结果

203
0x8049780
0x8049aac

但它应该给出 8048780+4 = 8048784 是对的..我是不是漏掉了什么

最佳答案

这对我有用:

 void foo(cfg * ptr)
 {
     printf("%zu\n", sizeof(*ptr));
     printf("%p\n", ptr);
     printf("%p\n", (void *)((char *) ptr + 4));
 }

然后:

 $ ./a.out 
 203
 0x7fffb6d04ee0
 0x7fffb6d04ee4

当你单独使用 (ptr + 4) 时,你实际上得到了 (ptr + 4 * sizeof(cfg)),因为指针运算与pointee,正如有人已经评论过的那样。

此外,地址应使用格式说明符 %p

关于c - 如何将结构视为内存位置并使用指针分别访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32076373/

相关文章:

c - 在递归调用中给出指针参数

matlab - 如何在Matlab中画出这种树状的点阵结构?

SVN项目结构

c - 两个大数相加只用C

c - for 循环超出其限制

c - 缓冲区溢出c(获取函数)

c - 指向char或char数组的指针

c++ - 打印时前一个指针的值不同

c - C 中的文件正在识别不必要的行

java - 在为树数据结构创建树类时是否强制使类节点静态