-6

I am pretty new to programming . And I am coming across this declaration a lot. Say for example:

char *x = "geeksquiz";

Does this mean that x holds the address of first element of the string,i.e, the character 'g' ?

If so then consider the following example:

char *str1 = "geeks"; 
char *str2 = "forgeeks"; 
printf("str1 is %s, str2 is %s", str1, str2);

Output is:

str1 is geeks, str2 is forgeeks

How come printf statement prints str1 is geeks and str2 is forgeeks , if they hold addresses respectively ? or is it the placeholder %s that's instructing the printf to print the string literals ?

2 Answers2

1

Does this mean that x holds the address of first element of the string,i.e, the character 'g' ?

Yes.

is it the placeholder %s that's instructing the printf to print the string literals ?

Yes.

To be more specific, %s is not limited for string literals. It is for printing null terminated srings - which string literals are. Also, it's called a format specifier.


Considering you've used the tag, note that the expression char *x = "geeksquiz"; is ill-formed in C++. In C++, the string literal is an array of const char and it doesn't decay to a pointer to non-const char. It is well formed in C, because in that language string literals are non-const.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

If this is used in c language then x holds the address of string first character 'g'. You can print it using this code.

    #include<stdio.h>
    int main(){
    char *x="geeksquiz";
    printf("%c",*x);
    return 0;
    }

Output : g

V2K
  • 23
  • 1
  • 10