user707549
user707549

Reputation:

how to assign a value using address?

I was asked a question during an C Language interview. the question is:

int *point;
'0x983234' is a address of memory;//I can not remember exactly

how could we assign 20 to that memory? it looks likes a embedded programming question, can anyone explains me?

Upvotes: 2

Views: 30016

Answers (3)

milad mohtashami
milad mohtashami

Reputation: 31

I use this approach to do it.its benefit is that you don't need another variable (pointer). assume that you want to set a variable of type uint8_t at adress 0x00002dbd to 200. you could code simply:

*(uint8_t*)0x00002dbd=200;

or if you a have uint32_t variable (not a pointer) that contains the address of the your uint8_t variable, you can do this:

uint32_t x;
x=0x00002dbd;    
*(uint8_t*)x=200;

it doesn't matter what type your target variable is. just the type instead of uint8_t part.

Upvotes: 3

user405725
user405725

Reputation:

First you have to set your pointer to the right address (so that it points where you need it to). Then, to write at that address, you dereference the pointer and do assignment. It will look something like this:

int main ()
{
        volatile int *point = (int *)0x983234;
        *point = 20;
        return 0;
}

Please note volatile keyword. It is recommended to use it so that compiler doesn't make any assumptions and optimize it.

If you have larger chunk of data to store, use memcpy or memmove with that address to copy data from/to it, like this:

#include <string.h>

int main ()
{
        const char data[] = "some useful stuff";
        memcpy ((char *)0x983234, data, sizeof (data));
        return 0;
}

Upvotes: 6

Jim Clay
Jim Clay

Reputation: 1003

I suspect that it is an embedded programming question, and that you are misremembering it slightly. It was probably something like-

int *point = (int *) 0x983234;
*point = 20;

Embedded programmers do do stuff like that when there is a register that they want to read/write at address 0x983234.

Upvotes: 9

Related Questions