Prayas Bansal
Prayas Bansal

Reputation: 97

How to access a character in a character array

#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

Answers (3)

Vlad from Moscow
Vlad from Moscow

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

sarkasronie
sarkasronie

Reputation: 345

Use %c:

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

Upvotes: 3

Rahul
Rahul

Reputation: 18557

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.

Upvotes: 1

Related Questions