Indexing Char *

Posted on 2006-03-31
Medium Priority
Last Modified: 2010-04-15
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.
Question by:cfans
  • 2
  • 2

Author Comment

ID: 16345126
The reason I'm indexing in is to then change a letter within it.
LVL 20

Accepted Solution

ikework earned 800 total points
ID: 16345157
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 :)

Author Comment

ID: 16345275
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"
LVL 20

Expert Comment

ID: 16345381
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 ...


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question