Search code examples
cstringpointersruntime-erroralphabet

C function to print the alphabet using pointers


I have this code:

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

int main()
{
    char* abc = "abcdefghijklmnopqrstuvwxyz";
    printArray(abc, 26);
    return 0;
 }

That is suppose to print all the English alphabet letters, but there is a run-time error and I need to find why it is caused and how to fix it. I have tried anything that came up to my mind to fix it but nothing helped, it just prints a lot of random stuff. Thanks for the help in advance. P.S: This is not a code I wrote, I just need to find the mistake and fix it.


Solution

  • The condition to stop

    p < p + len
    

    will not be false as you do p++ in every iteration of the loop. You eventually access invalid memory locations and this causes Undefined Behavior and This what is causing the runtime-error. To fix it, use another variable

    char *tmp=p+len;
    

    and change the condition to

    p < tmp
    

    An alternative way would be to decrement len in each iteration. Exit the loop once len is zero:

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