How to access a character in a character array

Prayas Bansal Source
#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".



answered 7 days ago sarkasronie #1

Use %c:

printf("%c", *(*(name+2)+7));

answered 7 days ago rahulsm #2

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.

answered 7 days ago Vlad from Moscow #3

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


Take into account that according to the C Standard the function main without parameters shall be declared like

int main( void )

comments powered by Disqus