cstringpointersmemory

Storing a string at some given address stored in a pointer


I have assigned a pointer ptr with a value of 0x8000_0000 which specifies some given address. Now, I want to store "Hello World" string at this address location.

How can I do this ?


Solution

  • If this address is a starting address of an area in the memory where it is valid for you to write 12 bytes (the length of the string with the zero termination),
    then you can use strcpy in the following way:

    strcpy((char*)ptr, "Hello World");  // you can drop the cast if `ptr` is already a `char*` or a `void*`
    

    But note that if this memory area is not valid, this will cause undefined-behavior.