Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why a pointer in C can print his content without dereference? [duplicate]

I created a program in which I noticed two things

  1. I used the address of pointer to print the whole word and It works but when I replaced s with *s it did not work (why is this happened?) (I used address in printf not *s the content)
  2. When I used pointer to pointer to print the character I could not print anything (I mean when I replaced %s with %c

My code :

#include<stdio.h>


int main ()
{
    char str[10]="PinkFloyd";
    char *s;
    char **s1;
    
     s=&str[0];
     
     s1=&s;
     
     printf("the word is using pointer to pointer %s",*s1); //why if I used %c does not print the first character 
     printf("\n");
     printf("the word is using s pointer %s",s); // why if I had replaced with *s does not print anything
    
    
    
    return 0;
}
like image 762
vgag1997 Avatar asked Nov 27 '25 12:11

vgag1997


1 Answers

You don't need * to print a string because, in effect, printf does it for you.

When you use %s with printf, it turns out you do not actually pass your string to printf. You pass a pointer to the string's first character, and printf takes care of stepping along the string and printing all its characters.

This is no different, though, from the way strings are handled everywhere in C. Strings are arrays, but arrays are "second class citizens" in C, which basically means you never pass them around in their entirety. Pretty much every library function in C that works with strings, works with them by using pointers to their first characters.

If you call

printf("%s", *s);      /* WRONG */

it doesn't work. *s gives you the contents of the pointed-to pointer, which is the character 'P'. But %s wants a pointer, not a character.

You might also find this question and its answers interesting.

like image 191
Steve Summit Avatar answered Nov 29 '25 07:11

Steve Summit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!