C语言 C for 用指针循环遍历数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13434177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:27:57  来源:igfitidea点击:

C for loop through array with pointers

cpointersloopsfor-loop

提问by TutenStain

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.

我是 C 新手,但我有 Java 和 Android 方面的经验。我的 for 循环有问题。它永远不会结束,只会继续下去。

char entered_string[50];
char *p_string = NULL;

gets( entered_string );

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

我知道 get 是不安全的,不推荐和弃用,但根据我的规范,我必须使用它。我想使用指针遍历每个元素。

回答by Cornstalks

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

你的测试应该是 *p_string != '\0';

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

p_string是一个指针,您的循环正在检查指针是否为!= '\0'. 您对值是否为 感兴趣!= '\0',并且要从指针中获取值,您必须使用 取消引用它*

回答by Diizzy

##代码##

Output:
54321
4321
321
21
1

输出:
54321
4321
321
21
1

回答by Nikolai Fetissov

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

它应该是*p_string != '\0'针对条件的 - 您需要取消引用指针。