0

Here p is a character pointer not an array! Yet compiler gave no warning or error?

    char  *p = "Vladimir";

closed as off-topic by Deltik, Máté Juhász, Anaksunaman, DavidPostill Sep 17 at 22:05

  • This question does not appear to be about computer software or computer hardware within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    This is the wrong site for your question - read the text of your tag c. That said, your code is completely correct: read K&R. – AFH Sep 17 at 11:42
  • @AFH Yeah that's what I'm asking why it is correct. Beacause pointer is a char pointer . So it must bot be able to hold the whole string ! – Da3kL10rd Sep 17 at 11:47
  • This question is better suited to stackoverflow.com – Mawg Sep 17 at 13:25
  • 1
    @Mawg okay I got it man – Da3kL10rd Sep 17 at 13:56
  • K&R is the standard definition of the C language by its designers, and your question is well explained there. I say again that you must read it. – AFH Sep 17 at 14:42
3

It's only a matter of interpretation: *p is a character, you are right.

But the C routines from string.h or stdio.h will interpret p as pointer to the first character of a "string", with the following characters at consecutive addresses p+1, p+2 and so on, and the convention that a zero character '\0' (which is added implicitly by the compiler!) will terminate the "string".

I use quotes for "string" here, because C (in opposite to C++) has no native string type at all.

C uses exactly this pointer-to-character for "strings". As a consequence, C "strings" cannot contain '\0' characters, and always use one char more space than visible at the first glance.

  • Please do not answer off-topic questions. – DavidPostill Sep 17 at 22:07
3

The characters "Vladimar" are stored as a string literal, which is stored in the read-only segment of the executable image. The pointer is assigned to the start address of the string literal.

Note the compiler null-terminates string literals. String handling functions in C depend on the null terminator. When it is found, the function typically stops processing the string. So this works:

gets(p);

It is a quirk of C that the non-const pointer can be assigned to a read-only string literal (In C++, it is invalid to do so).

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

  • Please do not answer off-topic questions. – DavidPostill Sep 17 at 22:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.