-1
#include <stdio.h>

int main(){
    char *ch = "Hello, World";//character pointer pointing to a string without declaration.
    printf("%s", ch);//printing the string without <i>dereferencing</i> it.
}

I saw an example in a book, with code as given above. I don't understand how a character pointer points to a string without declaring a string first.
Also there is no dereference operator used to print the string.

alk
  • 69,737
  • 10
  • 105
  • 255
WeirdoTechy
  • 9
  • 1
  • 6
  • I would rather use *str* or *s* since the variable is a pointer and not a character. Also you want to declare it as `const char *str` to prevent modification of the string constant it points to. – August Karlstrom Feb 04 '17 at 10:29

3 Answers3

2

As stated very well by @tryurbest, Why it works with pointers:

When you say char * ch in C, you are allocating a pointer in the memory. When you write char *ch = "Hello, World";, you are creating a string literal in memory and making the pointer point to it. When you create another string literal "new string" and assign it to ch, all you are doing is changing where the pointer points.

On the other hand, for added information, Why it doesn't work with arrays:

When you say char ch1 [] = "Hello, World", you are creating a string literal and putting it in the array during its definition. It is ok to not give a size, as the array calculates it and appends a '\0' to it. You cannot reassign anything to that array without resizing it.

Hope this helps to clarify some things.

  • _"You cannot reassign anything to that array without resizing it"_ What does this mean? – Emil Laine Feb 04 '17 at 17:11
  • What I mean is that you can't do `ch1 = "hello"` where you are assigning something to the new array. –  Feb 04 '17 at 17:20
1

"Hello, World" is a string literal or read only memory store in data block. A variable ch is pointer to char, which is initialized with the location of the first character.

msc
  • 33,420
  • 29
  • 119
  • 214
0

That's simply how printf works with a const char* argument. (Your pointer actually points to const data.)

Starting at the memory location denoted by the pointer, it prints character by character until a NUL terminator is reached.

The C standard library string functions all work in this way. Simply put it's how the language models strings.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483