4

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.

0

3 Answers 3

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
3
    char str[] = "54321"; 
    char *p;  
    p = str;   
    for (p; *p != '\0';++p)
    {
         printf("%s \n",p);
    }

Output:
54321
4321
321
21
1

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.