简体   繁体   中英

Print the characters by iterating in c

#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 , ie, the character p points to:

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

The function outputs just one character if the passed pointer p is not equal to NULL because any loop in the function is absent. The function contains only if statement that checks the pointer p.

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

You need a loop that will output characters of a pointed string.

But for starters the function parameter should have the qualifier const because the pointed string is not changed within the function.

The function can look the following way

void fun( const char* p)
{
        if ( p )
        {
            while ( *p ) putchar( *p++ );
        }
}

But the function will be more general if it will have a second parameter that specifiers a file. For example

FILE * fun( const char* p, FILE *fp )
{
        if ( p )
        {
            while ( *p ) fputc( *p++, fp );
        }

        return fp;
}

In this case you can output a string in a file.

Here is a demonstrative program

#include <stdio.h>

FILE * fun( const char* p, FILE *fp )
{
        if ( p )
        {
            while ( *p ) fputc( *p++, fp );
        }

        return fp;
}

int main(void) 
{
    fputc( '\n', fun( "Y32Y567", stdout ) );
    
    return 0;
}

Of course you could output a string as whole without a loop with one statement. For example

#include <stdio.h>

FILE * fun( const char* p, FILE *fp )
{
        if ( p )
        {
            fputs( p, fp );
        }

        return fp;
}

int main(void) 
{
    fputc( '\n', fun( "Y32Y567", stdout ) );
    
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM