简体   繁体   中英

Can you copy data to `char*` pointer without allocating resource first?

I have seen an example here: http://www.cplusplus.com/reference/string/string/data/

 ...
 std::string str = "Test string";
 char* cstr = "Test string";
 ...
 if ( memcmp (cstr, str.data(), str.length() ) == 0 )
      std::cout << "str and cstr have the same content.\n";

Question > How can we directly copy data into the location where the pointer cstr pointed to without explicitly allocating space for it?

memcmp is comparing the content of memory pointed to by the two pointers. It does not copy anything.

[EDIT] The question was edited to add a concrete question. The answer is: you need the pointer to point to memory allocated one way or another if you want to copy data there.

How can we directly copy data into the location where the pointer cstr pointed to without explicitly allocating space for it?

You cannot, using an initialisation from a character string literal.

That memory will be placed in the static storage section of your program, and writing there is calling undefined behaviour (merely an exception in your particular compilers implementation).

lets assume that you used memcpy(cstr,x,...) instead of memcmp.

You use phrase 'without allocating resource first'. This really has no meaning.

For memcpy to work cstr must point at valid writable memory.

so the following work

char *cstr = new char[50];
char cstr[50];
char *cstr = malloc(50);

The following might work but shouldnt

char *cstr = "Foo"; // literal is not writable

This will not

char *cstsr = null_ptr;
char *cstrs; // you just might get lucky but very unlikely

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM