zwerg4
zwerg4

Reputation: 330

Address array with a pointer variable

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?

Upvotes: 0

Views: 97

Answers (2)

Lundin
Lundin

Reputation: 213358

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;

Upvotes: 7

wookiekim
wookiekim

Reputation: 1176

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.

Upvotes: 0

Related Questions