Quotenbanane
Quotenbanane

Reputation: 265

C char pointer get a specific character

probably a dumb question but how do you access a specific character in a char pointer?

I've tried following...

char *pointer = "Hello";
printf("%s", pointer); // prints "Hello"
printf("%s", &pointer[0]); // also prints "Hello"

But what I want is printf(???) => "H". A single character. Or the "e". How is that possible?

Upvotes: 0

Views: 9225

Answers (3)

some user
some user

Reputation: 1775

You want to access the char of char* simply use [] operator, just like arrays.

char *pointer = "Hello";
printf("%s", pointer); // ok
printf("%s", &pointer[0]); // wrong way of accessing specific element (it is same as the base address.., thus %s prints the whole thing)

Instead you're accessing the address of the first element of char* or string literal.. why!

printf("%c", pointer[0]); // use this one 

Just like arrays, access the required element.

However, to get it better, notice here:

#include <stdio.h>

int main() {

    char *pointer = "Hello";
    printf("%s\n\n", pointer); // ok
    printf("%c", pointer[0]); 

    printf("%p == %p\n", (void *)&pointer[0],(void *)pointer);
    // cast to void * to avoid undefined behavior 
    // pointed out by @ex nihilo 


    printf("%p", pointer+1); 


    return 0;
}

Output:

Hello
H0x55da21577004 == 0x55da21577004
0x55da21577005

as you can see, the pointer holds the address of the first element which is: &pointer[0] thus you get the same output.

Upvotes: 1

SPlatten
SPlatten

Reputation: 5760

    char* pointer = "Hello";

Creates a pointer and assigns it to the base address of "Hello".

pointer and &pointer[0] are the same thing.

pointer[n] takes the address of "Hello" and offsets it by the number 'n', be sure not to index of the end of the address or you will read rubbish.

So:

    pointer[0] = 'H'
    pointer[1] = 'e'
    pointer[2] = 'l'
    pointer[3] = 'l'
    pointer[4] = 'o'
    pointer[5] = 0

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222724

pointer is a pointer to char, also called a char *.

After char *pointer = "Hello";, pointer points to the “H”.

When printf is given %s, it takes a char * and prints all the characters it finds starting at that location, until a null character is seen.

To tell printf to print a single character, pass it the actual character value (not a pointer) and use %c:

printf("%c", *pointer);

or:

printf("%c", pointer[0]);

or, for the “e” instead of the “H”:

printf("%c", pointer[1]);

Upvotes: 5

Related Questions