-2
char *p = "hello";  
printf("%c",*p); //output would be ***h***
printf("%s",p);  //output would be ***hello***

At line 2 why we have to use *p to print a char and at line 3 we have to use p to print a string.

Also at line 1 how the string is stored in memory.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • 6
    http://stackoverflow.com/a/18479996/1814023 –  Dec 05 '13 at 08:29
  • 1
    `const char *p = "hello"` or `char p[] = "hello"`. A `char *p = "hellp"` is a segfault waiting to happen. See [this](http://stackoverflow.com/questions/6492410/assigning-string-literals-to-char), for example. – Eran Dec 05 '13 at 08:33
  • take `'*p'` out of `'char*p'` and you get `'char'`, i.e., the first `'printf'` receives a char, now take `'p'` from `'char*p'` and you get `'char*'`, i.e., the second `'printf'` receives a char pointer, don't know if this is by design – alexgirao Dec 05 '13 at 08:40

3 Answers3

2

an array is simply a pointer to a block of memory filled sequentially with items of a specific type.

p in this instance is a pointer to the first character in that array,

*p will dereference the pointer, which will return the item at that specific location (i.e. the first character in the string.

The most common string representation in c (and the one used by %s) is null-terminated strings. I.e. the string will start at p and continue until it hits a null (\0) value.

Oliver Matthews
  • 7,497
  • 3
  • 33
  • 36
1

"hello" is saved in a read only memory of your system

p is a pointer that it is pointing at the beginning of your "hello" memory. so it's pointed in the first element of the memory.

*p return the content of the memory which p is pointing on. and p is the address of the first element of the "hello" memory so *p will return 'h'

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
1

String are stores in memory by a chain of of characters and are terminated by a 0 character. For example, if you have a string literal "Hello", that string would be stored in memory as a char* array of {'H', 'e', 'l', 'l', 'o', '\0'}.

Because of this, if you access the array ( *array ), you only access the first character of the array. You can loop through the array until you find the \0 - char to know where the string ends.

user3067395
  • 560
  • 6
  • 17