Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C for loop through array with pointers

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.

like image 425
TutenStain Avatar asked Dec 04 '22 13:12

TutenStain


1 Answers

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

like image 130
Cornstalks Avatar answered Dec 27 '22 17:12

Cornstalks