Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

prints the content of an array through a function

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading