user1907266
user1907266

Reputation: 21

What is the effect of dereferencing a string literal in C?

#include<stdio.h>

int main()
{
    printf("%c",*"abcde");
    return 0;
}

how 'a' will be the output for this program? let me know why the output is 'a' when compiled in turbo c..and what does '*' here imply?

Upvotes: 2

Views: 1890

Answers (3)

Justin R
Justin R

Reputation: 1

Remember the printf function takes in a const char* as a parameter, and as said above a string is just an array of char values. When passing an array in c++ the compiler takes it as a pointer to the first element of the [].

Ex. string nums[] = {"one", "two); string* p2 = nums; //Totally valid and how the compiler would sees this would be an address to "one".

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

"abcde" is a string literal, which is an array of characters (char[]). It is typically placed in a read-only data section of the program. If you were to pass that to printf, the compiler is actually passing the address of that array to printf.

However, here you are de-referencing that pointer, which passes just the first character.

Here is an equivalent, more verbose version that may make more sense:

const char* str = "abcde";    // str is a char* pointer to "abcde"
char c = *str;                // De-reference that pointer - in other words,
                              //   get me the char that it points to.
printf("%c", c);              // Pass that char to printf, where %c is
                              //   expecting a char.

Upvotes: 2

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215201

"abcde" is a string literal and thus has array type. In any context but sizeof or the operand of &, an array decays to a pointer to its first element. Thus, when used as the operand of the unary * operator, "abcde" is evaluated to a pointer to the "a" at the beginning of the string, and the * operator dereferences that pointer, obtaining the value 'a'. Passing this value (an integer) to printf for formatting with the %c format specifier causes printf to print the corresponding character, "a", to stdout.

Upvotes: 2

Related Questions