0

I try to store an address in a variable. This address should be like an array. Every new data I get from the input should be saved in the address of the variable + index.

int RF = 0x15; // address array
int R2 = 0 ; // index
*(RF + R2) = 100;

But When I compile it I get this error:

error: invalid type argument of unary ‘*’ (have ‘int’)

Does anyone have an Idea why?

2
  • I think it would be easier to use the construct provided by C than trying to implement something around what C is meant to be. I.e. use a variable and an array, do not tinker with pointers if you can avoid it. Commented Apr 13, 2018 at 6:47
  • 1
    You are accessing memory mapped peripherals on an embedded device, aren't you? If yes (also if not), please explain more about your environment in your question. Commented Apr 13, 2018 at 7:01

2 Answers 2

7

To access memory directly, you need to convert the integers to a pointer. This is not done implicitly. So you must write something like

int RF = 0x15; // adresse array
int R2 = 0 ; // index
*((int*)RF + R2) = 100;

This does however assume that a valid int exists at that address, which doesn't seem very likely on most systems. On some systems the address must also be aligned.

So code like this would probably just make sense if the memory accessed was a hardware register, in which case the pointer should be changed to volatile. And the default int type is signed so that would make no sense either, something like uint16_t or uint32_t should be used instead. Example:

*(volatile uint16_t*)0x15 = 100;
Sign up to request clarification or add additional context in comments.

Comments

0

The other answers may be able to fix your error, but even if you manage to compile your program using

int* RF = (int*)0x15; 

you will still run into a segmentation fault if you try to access address 0x15. It is just not meant for a user like you to access directly.

Learning about dynamic memory allocation in C could help.

2 Comments

This answer is making a whole lot of assumptions of the memory map. 0x15 can be accessed just fine on a whole lot of systems, most notably 8 or 16 bit microcontrollers without virtual memory or alignment concerns. And what does dynamic allocation have to do with anything?
you are absolutely right. Sorry about that. Just mentioned the dynamic memory allocation part for the 'address acting like an array".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.