C for loop through array with pointers

40,718

Solution 1

Your test should be *p_string != '\0';

p_string is a pointer, and your loop is checking if the pointer is != '\0'. You're interested in if the value is != '\0', and to get the value out of a pointer you have to dereference it with *.

Solution 2

    char str[] = "54321"; 
    char *p;  
    p = str;   
    for (p; *p != '\0';++p)
    {
         printf("%s \n",p);
    }

Output:
54321
4321
321
21
1

Solution 3

It should be *p_string != '\0' for the condition - you need to de-reference the pointer.

Share:
40,718
TutenStain
Author by

TutenStain

Updated on January 20, 2020

Comments

  • TutenStain
    TutenStain over 4 years

    I'm new to C but I have experience in Java and Android. I have a problem in my for loop. It will never end and just go on and on.

    char entered_string[50];
    char *p_string = NULL;
    
    gets( entered_string );
    
    for( p_string = entered_string; p_string != '\0'; p_string++ ){
        //....
    }
    

    I know that gets is unsafe, not recommended and deprecated but according to my specs I have to use it. I want to loop through each element by using pointers.

  • TutenStain
    TutenStain over 11 years
    I have tried to solve this problem for a while now. Works perfectly Thank you! It takes time to grasp pointers after coming from 2 years java programming w/o using references on daily basis.