Difference between %s and %c

In C, a string is nothing but only an array of characters. So we have no starting pointers in C. Its the character pointers that are used in case of strings too.

Now, in case of the string, when we point a pointer to a string, by default it holds the address of the first character of the string. Lets try to understand it better.

#include <stdio.h>
int main(){
  char *ptr = "I am string";
  printf("%c      %s",*ptr, ptr );
  return 0;
}

Output : I       I am string
Explanation : The string, ‘I am string’ in memory is placed as :






Since characters occupy one byte each, so they are placed like above in the memory. Note the last character, its a null character which is placed at the end of every string by default in C. This null character signifies the end of the string.

Now coming back to the point, any character pointer pointing to a string stores the address of the first character of the string. In the code above, ‘ptr’ holds the address of the character ‘I’ ie 1000. Now, when we apply the ‘value of’ operator ‘*’ to ‘ptr’, we intend to fetch the value at address 1000 which is ‘I’ and hence when we print ‘*ptr’, we get ‘I’ as the output.

Also, If we specify the format specifier as ‘%s’ and use ‘ptr’ (which contains the starting address of the string), then the complete string is printed using printf. The concept is that %s specifier requires the address of the beginning byte of string to display the complete string, which we provided using ‘ptr’ (which we know holds the beginning byte address of the string). This we can see as the last print in the output above.

No comments:

Post a Comment