1

This code print Only first letter i.e 'H'

#include <stdio.h>

int main(void)
{
    char *s = "Hello";
    printf("%c\n", *s);
}

But this return 'Hello'

#include <stdio.h>

int main(void)
{
    char *s = "Hello";
    printf("%s\n", s);
}

changing %c to %s will return an error in the first code
changing %s to %c will return an error in the second code

In my understating *s is dereferencing operator i.e what value we find when you go to that address and s is what store in s(address of 'H'). Please, someone explains this.

1 Answer 1

2

printf("%c\n", *s); is the same as printf("%c\n", s[0]);

By definition of printf, the %c format specifier in printf expects a character. So, *s says go to the address stored in s, and give me the character there. The square bracket notation says "get the address of s and add 0 to it, then dereference it to get its value."

printf("%s\n", s);

By definition of printf, the %s format specifier expects a pointer to a string. That's why you give it s as s is the pointer.

4
  • So when we use FILE *card; card = fopen() here what is difference between *card and card.
    – d0020002
    Commented Oct 9, 2017 at 0:55
  • The first one you are declaring a FILE pointer called card. In the second, you are setting the results of fopen to that pointer (fopen returns a pointer). card is a pointer that points to a FILE.
    – curiouskiwi
    Commented Oct 9, 2017 at 0:58
  • In my understanding dereference operator(*) change the data to that address where pointer is pointing. So why it cant be done like this FILE *card; *card = fopen(); Here card is pointing to FILE and *card(dereference operator) is storing data where pointer is pointing. What's wrong in this?
    – d0020002
    Commented Oct 9, 2017 at 1:12
  • fopen returns a FILE * or NULL. You wouldn't be able to compile if you tried to store a FILE * in *card since *card is not a pointer.
    – curiouskiwi
    Commented Oct 9, 2017 at 1:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .