• C

Indexing Char *

Say i've got:
char * word = "hello";

how do I index through hello.

I wanted to use a for loop going through the word one character at a time.
I thought that word[0] would give me "o" but it gives the whole thing "hello".
So i'm not sure how to index through.
Who is Participating?
char *word = "hello";
char *pIter = word;
char letter;

while( pIter != NULL )
    letter = *pIter;
    printf( "%c", letter );

here are the items of the array
word[0] = 'h';
word[1] = 'e';
word[2] = 'l';
word[3] = 'l';
word[4] = 'o';
word[5] = '\0'; // << terminating zero-byte

hope it helps :)
cfansAuthor Commented:
The reason I'm indexing in is to then change a letter within it.
cfansAuthor Commented:
Ike, thanks.. I can't seem to get change an entry in it.. have any idea how to change.. like 'h' to 's'
to ultimately make the work then "sello"
tdeclare your strings this way:

char word[] = "hello";

word[1] = 'x';

but this is a static-sized string, don't put more than 5 letters in it!!
otherwise use dynamically allocated arrays ...

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.