user3180902
user3180902

Reputation:

Why the complete character array is getting printed not the first character?

This is the source code

char target[80]="hello", *tar;
tar=⌖
printf("%s",tar);  //printing hello

tar is getting the address of target[0] then why it is printing the whole character array.

Upvotes: 0

Views: 80

Answers (4)

fomy
fomy

Reputation: 9

%s indicates printing characters between the character 'tar' points to and next '\0' .

printf("%c",*tar);

will print what you need.

Upvotes: 0

Ned
Ned

Reputation: 957

C strings are null terminated. When you pass the address of the first character in an array of characters representing a string to printf and tell it to format the output as a string using %s, it will print all of the characters beginning at the address of the first character until a null (NUL) character, '\0', is reached.

Upvotes: 0

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

when u say %s and specify a starting memory(or any intermediate) of the string it gets printed till it encounters '\0' character.

consider

    char *name = "Hello";

will be stored internally as Hello\0

so if u need a single character go for %c.

Upvotes: 2

Sarwan
Sarwan

Reputation: 657

Use %c to print a single character and %s is used to print a string.

Upvotes: 1

Related Questions