Indexing Char *

Posted on 2006-03-31
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

    Author Comment

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

    Accepted Solution

    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

    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

    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 ...


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Suggested Solutions

    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…
    Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
    The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

    758 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

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now