Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello
How can i put data in a specific address , let say i want to put the number 8 in address 2000

Thanking you all in advance
Posted

int *pInt = (int *)2000;
*pInt = 8;


Regards
Espen Harlinn
 
Share this answer
 
v2
Comments
tctc7 13-Jan-11 13:16pm    
Thank you but
I've got an error in this line int *pInt = 2000; :

2 IntelliSense: a value of type "int" cannot be used to initialize an entity of type "int *"
Sergey Alexandrovich Kryukov 13-Jan-11 14:22pm    
Nothing to do with IntelliSense....

Yes, Espen, it would not compile, unfortunately -- not a big deal, though. See my answer.
Espen Harlinn 13-Jan-11 14:23pm    
Sorry - forgot to cast the intergaer value i.e. (int *)2000
fjdiewornncalwe 13-Jan-11 14:27pm    
+5 Same reason as for SAKryukov's answer... Cheers.
Sergey Alexandrovich Kryukov 13-Jan-11 14:30pm    
Thank you guys.
Damn C++!
Hi,

You got valid C answers.
C++ provides the placement new syntax for your goal:
C++
// Create an int of value val at address buffer with placement new
int* p = new (buffer) int(val);

For your question it would be:
C++
int* pad = new ((int*)0x2000) int(8);


cheers,
AR
Edit: added unparametered code.
 
Share this answer
 
v2
Comments
Chris Meech 14-Jan-11 10:51am    
What's the declaration of buffer look like?
Alain Rist 14-Jan-11 15:52pm    
int* buffer = (int*) a_valid_address; :)
Espen's shown you how to do it. But you should not be putting data into arbitrary memory locations unless you are sure you know what you are doing. It's a known recipe for disaster to do that.
 
Share this answer
 
Comments
Chris Meech 13-Jan-11 14:32pm    
Nish's comments are quite valid. There is no explanation for why someone has one voted it.
Nish Nishant 13-Jan-11 14:37pm    
Ironically it was someone with Gold status too :-)
C++
int *pInt = (int*)2000;
*pInt = 8;


Of course you should be careful with address. This answers your question, but...

In a normal application, this statement is useless, because you almost never have any constant addresses constants. It can be the case in very old systems or with something more exotic like embedded controllers.
 
Share this answer
 
v2
Comments
Espen Harlinn 13-Jan-11 14:25pm    
5+ for remembering the cast :)
fjdiewornncalwe 13-Jan-11 14:26pm    
I'm guessing that this gentleman is in an early class on pointers. Taking this into account, I like your answer being very clear and concise.
Sergey Alexandrovich Kryukov 13-Jan-11 14:32pm    
Thank you.
Probably you're right about the classes. Who cares though...
you must read some programming book first. Don't try to do that. :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900