Search code examples
c++arrayspointersiterator

Iterate elements of array using pointer


I try execute code:

char* m[3] = {"123", "456", "789"};
for(char* st=*m; st!=0; st=*(m+1))
{
    cout <<st;
} 

but it hung up and print: 123456456456...


Solution

  • The loop you wrote is invalid

    char* m[3]={"123","456","789"};
    for(char* st=*m;st!=0; st=*(m+1))
    {
        cout <<st;
    } 
    

    Expression *m has type char * and array m does not contain NULL pointer. So condition st!=0; is wrong. And the pointer always will point the same element because expression st=*(m+1) gives always the second element of the array

    Also take into account that the correct definition of the array will be

    const char* m[3] = { "123", "456", "789" };
    

    because it is an array of pointers to string literals and string literals may not be changed.

    You could use simply the range based for statement

    const char* m[3] = { "123", "456", "789" };
    for ( const char* st : m )
    {
        cout <<st << std::endl;
    } 
    

    Or you could use iterators in the loop. For example

    const char* m[3] = { "123", "456", "789" };
    for ( auto it = std::begin( m ); it != std::end( m ); ++it )
    {
        cout << *it << std::endl;
    } 
    

    And you could use standard algorithm std::copy

    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    //,,, 
    const char* m[3] = { "123", "456", "789" };
    std::copy( std::begin( m ), std::end( m ),
               std::ostream_iterator<const char *>( std::cout, "\n" ) );