简体   繁体   English

为结构成员赋值

[英]assign value to struct member

Wwhy cant I not assign value like this为什么我不能像这样分配价值

A1->a |= 5;

#include <stdio.h>

typedef struct {
    int a;
    int b;
    int c;
} A;

int main(){
    A *A1 = (A *) 0x100; //this is for example, an address of a register

    printf("A1.a is at %p\n", &(A1->a));
    printf("A1.b is at %p\n", &(A1->b));
    printf("A1.c is at %p\n", &(A1->c));

    A1->a |= 5; //this line doesnt work
    printf("A1.a = %d ", A1->a);
    return 0;
}

A1->a |= 5; this line doesnt work, cant any body help me understand why?这条线不起作用,任何人都不能帮助我理解为什么吗? I am trying to learn embedded programing and its programming style.我正在尝试学习嵌入式编程及其编程风格。

A *A1 = (A *) 0x100;

Your problem is this line.你的问题是这条线。 You cannot reference to an address that you do not own it.您不能引用不属于您的地址。 You do not know in this address, you can read or write the data.你不知道在这个地址,你可以读取或写入数据。

you can reference to an address of a variable:您可以引用变量的地址:

A A0;
A *A1 = &A0;

If the code is supposed to run on machine with Memory Management Unit active, then you will end up with a segmentation fault because the address you're trying to access is not mapped to your process.Keep in mind, you cannot access memory beyond the memory space you've been allocated (unless you request it, malloc, mmap, etc).如果代码应该在 Memory 管理单元处于活动状态的机器上运行,那么您最终会遇到分段错误,因为您尝试访问的地址未映射到您的进程。请记住,您无法访问 memory 超出memory 空间已分配给您(除非您要求,malloc、mmap 等)。

If it is supposed to run on a machine without MMU active (on MCU) then you can freely access any memory address (unless you do not have any Memory Unit Protection active for that region).如果它应该在没有激活 MMU 的机器上运行(在 MCU 上),那么您可以自由访问任何 memory 地址(除非您没有为该区域激活任何 Memory 单元保护)。 Basically you're trying to access three registers (0x100, 0x104, 0x108, suppose you run on 32 bit machine).基本上,您正在尝试访问三个寄存器(0x100、0x104、0x108,假设您在 32 位机器上运行)。 Please take into account that "int" is a signed number, what happens if your register has bit 31 set to "1"?请注意“int”是一个有符号数,如果您的寄存器将第 31 位设置为“1”会怎样? The result will be interpreted as signed.结果将被解释为已签名。 Now try to use bitwise operation on signed numbers.!!!现在尝试对有符号数使用按位运算。!!! (certainly not the result you're expecting) . (当然不是你期望的结果)。

#include <stdint.h>

typedef struct {
   uint32_t a;
   uint32_t b;
   uint32_t c;
} A;

volatile A *A1 = (volatile A*)0x100;

Just to make sure, do you really want to use bitwise?只是为了确定,你真的想按位使用吗?

A1->a | = 5 ; // if a = 1 => a = 7

If you're expecting to set the 5th bit, then you need to do:如果您希望设置第 5 位,那么您需要执行以下操作:

A1->a |= (1 << 5); // if a = 1 => a = 33

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM