0

From the K&R C book,

There is an important difference between these definitions:

char amessage[] = "now is the time"; /* an array */  
char *pmessage = "now is the time"; /* a pointer */ 

amessage is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed but amessage will always refer to the same storage. On the other hand, pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.

In this context, they are saying amessage is an array located at an immutable address that contains enough storage. Makes sense.

Here's the part I don't get: pmessage is a pointer pointing to a string constant. But where is this string constant located? Is memory set aside by the computer automatically? How can modifying the string change where pmessage is located? And why isn't the string constant a character array? It was to my understanding C wasn't able to process an entire string of characters as one unit.

dav
  • 626
  • 4
  • 21
  • 2
    I'd recommend reading the C11 draft standard n1570, *6.4.5 String literals*. – EOF May 01 '17 at 15:44
  • A char array is modifiable; a literal (constant! the word says it all) is not modifiable. – Paul Ogilvie May 01 '17 at 15:44
  • There are already may questions and good answers are here on SO. – haccks May 01 '17 at 15:44
  • @PaulOgilvie Detail: code that attempts to modify a _string literal_ is _undefined behavior_. It might "work", it might not - it is UB. In either case, it is not good code. C does not defined a _string constant_ as quoted in K&R. – chux - Reinstate Monica May 01 '17 at 16:09

0 Answers0