Home > front end >  prints the content of an array through a function
prints the content of an array through a function

Time:03-16

this is the code: the code needs to send the array to the function and the function will print but it seems there is run time error

#include <stdio.h>
#include <string.h>

void printArray(char* p, int len)
{
    for (p; p < p   len; p  )
    {
        printf("%c", *p);
    }
    printf("\n");
}

int main(void)
{
    char* msg = "hi jyegq meet me at 2 :)"; 
    printArray(msg, strlen(msg));
    getchar();
    return 0;
}

CodePudding user response:

for (p; p < p   len; p  )

This condition is all the time true, as you do not modify len and p is identical with p, even after mutatations. You need to define a new pointer q that is initially equal to p and mutate only q.

void printArray(char* p, int len)
{
    for (char *q = p; q < p   len; q  )
        printf("%c", *q);
    printf("\n");
}

It is better to define char const* p, as there is no reason to mutate p.

CodePudding user response:

In this for loop

for (p; p < p   len; p  )

the condition is always evaluates to logical true (except the case when len is equal to 0 or has a negative value that invokes undefined behavior) because p is evidently less than p len.

The function can be declared and defined the following way

void printArray( const char *s, size_t len )
{
    for ( const char *p = s; p < s   len; p  )
    {
        putchar( *p );
    }
    putchar( '\n' );
}

Pay attention to the the pointer parameter should have the qualifier const because the pointed string is not changed within the function and the second parameter should have the type size_t. It is the return type of the function strlen.

  • Related