Home > Back-end >  I wrote a code in C that send a pointer to function to print it, but there is a time running error
I wrote a code in C that send a pointer to function to print it, but there is a time running error

Time:03-30

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:

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.

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.

  • Related