Daniel Sopel
Daniel Sopel

Reputation: 3733

Reading Address From Memory in C

I am trying to store the character at an address in a variable, but I have a compile error ( invalid type argument of unary ‘*’ (have ‘int’)).

int address = 4000;
char character = (char) *address

Why doesn't this code dereference the pointer to store the character at memory location 4000 and how can I fix it? Thanks.

Upvotes: 2

Views: 2903

Answers (5)

qPCR4vir
qPCR4vir

Reputation: 3571

char *address=(char*)4000;
char character = *address;

yours responsability what is in "4000"

Upvotes: 0

NPE
NPE

Reputation: 500167

Syntactically, you are looking for

char character = *(char*)address;

Whether this will do anything useful is another matter...

Some issues to ponder:

  1. int may or may not be wide enough to represent every valid address (on my system, it isn't).
  2. How do you know what's at address 4000 in your process's memory map?

Upvotes: 5

Jesus Ramos
Jesus Ramos

Reputation: 23268

You can't just attempt to address random memory addresses and expect it to work. Your program may possibly access a non mapped memory address and will just crash or cause yourself many problems later on but to do what you want.

char *address = (char *)4000;
char c = *address;

Upvotes: 2

ldav1s
ldav1s

Reputation: 16305

#include <stdint.h>
intptr_t address = 4000;
char character = *((char*)address);

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476940

Do this:

#include <stdint.h>
/* ... */
uintptr_t ip = 4000;                 // this is an integer
char character = * (char *)(ip);

Upvotes: 0

Related Questions