3
#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".

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

4

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 )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • " function main without parameters shall be declared like int main( void )" Or in some implementation-defined manner. That is, if you are assuming hosted implementation. On a freestanding implementation, the form of main is always implementation-defined. – Lundin Mar 14 '18 at 12:57
3

Use %c:

printf("%c", *(*(name+2)+7));
sarkasronie
  • 335
  • 1
  • 2
  • 15
1

You can use simple trick as follows,

printf("%c", name[2][7]);

And as you want character, you should use %c.
Here is working demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60