Printthecharactersbyiteratinginc

#include <stdio.h>

void fun(char *p) {
    if (p) {
        printf("%c", *p);
        p++;    
    }
}

int main() {
    fun("Y32Y567");
    return 0;
}

Output:Y

Expected Output:Y32Y567

My questions why it is not working the expected way?

回答

The function fun only prints one character if it enters the if. You probably meant to use a while loop, not a single if condition. Additionally, your condition is wrong - p evaluates to a true-thy as long as it's not NULL, which won't happen if you passed a string literal. You probably meant to test *p, i.e., the character p points to:

void fun(char* p)
{
        while (*p) /* Here */
        {
            printf("%c",*p);
            p++;    
        }
}


以上是Printthecharactersbyiteratinginc的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>