Question

What is difference between the following code?

1.

char *p;
strcpy(p,"String");

2.

char *p;
p = "String";

The pointer points to the same string, but is there any difference?

Was it helpful?

Solution

In order for the first operation to work, p must point to a writable block of memory at least 7 bytes in size. The second operation does not require it.

After the first operation the string remains writable: you can do this on the first string, but not the second:

*p= 's'; // Make the value all lowercase

The second pointer assignment points p to a memory of a string literal; writing to that memory is undefined behavior.

OTHER TIPS

(1) is a memory scribble and possibly a runtime error.

You cannot copy into memory you don't own (haven't allocated in some way).

In the first point you say you want to copy the string to the memblock p is pointing to

(so you have to make sure, there is enough space where the string can be copied to)

In the second case you just make p pointing to the read only address of "String".

p -> [S][t][r][i][n][g][0]

But you should get compiler warnings as far you don't declare p as p const *

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top