3

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?

xQuare
  • 1,293
  • 1
  • 12
  • 21
Devraj Jaiman
  • 83
  • 1
  • 2
  • 8

3 Answers3

6

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

(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).

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

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 *

dhein
  • 6,431
  • 4
  • 42
  • 74
  • hence in first String is copied to another location and then address is assigned to pointer. But in second direct address of String is assigned to p. – Devraj Jaiman Sep 14 '13 at 11:32