Reputation: 97
#include< stdio.h>
int main()
{
char *name[] = { "hello" , "world" , "helloworld" }; /* character array */
printf("%s", (*(name+2)+7));
return 0;
}
The above code prints out "rld". I wants to print only "r".
Upvotes: 3
Views: 392
Reputation: 310920
For starters you do not have a character array. You have an array of pointers. Also it would be better to declare the type of array elements like
const char *
because string literals are immutable in C.
And instead of the %s
specifier you need to use the specifier %c
to output just a character.
A simple and clear way to output the target character of the third element of the array is
printf("%c", name[2][7]);
Or using the pointer arithmetic you can write
printf("%c", *(*( name + 2 )+7 ) );
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
const char *name[] =
{
"hello" , "world" , "helloworld"
};
printf( "%c\n", *( * ( name + 2 ) + 7 ) );
printf( "%c\n", name[2][7] );
return 0;
}
Its output is
r
r
Take into account that according to the C Standard the function main
without parameters shall be declared like
int main( void )
Upvotes: 4