Question

I'm writing a version of strcmp that has the option of comparing strings only on the basis of space and alphanumeric characters (directory order) as well as the option of being blind to case distinctions (Kernighan and Ritchie page 121 5-16). So I came up with the following:

int strcmpdf (char* s, char* t)
{
    char a[100];
    char b[100];
    int i;
    int j;
    i = j = 0;
    if (directory){ /*compares strings solely on the basis of alphanumeric/space characters*/
        for (   ; *s != '\0'; s++)
            if (isalnum(*s) || isspace (*s) || *s == '\t' || *s == '\n')
                a[i++] = (fold && islower(*s))? toupper(*s) : *s;
        a[i] = '\0';
        for (   ; *t != '\0'; t++)
            if (isalnum(*t) || isspace (*t) || *t == '\t' || *t == '\n')
                b[j++] = (fold && islower(*t))? toupper(*t) : *t;
        b[j] = '\0';
        return strcmp(a,b);
    }else if (fold && !directory){/*folds upper and lower cases together*/
        for (   ; toupper(*s) == toupper(*t); s++,t++)
            if (*s == '\0')
                return 0;
        return toupper(*s) - toupper(*t);
    }else
        return strcmp(s,t);
}

This works fine and answers the question but problems start when I start using char pointers instead of arrays. When, instead of arrays a and b, I initialize char* a and char* b, and replace the a[i++] with *a++ on line 11 and 12 and b[j++] with *b++ on line 15 and 16, I get a segmentation fault. Why do I get this error when a+i is the address of a[i]?

Was it helpful?

Solution

When you declare an array such as 'char a[100]', it allocates 100 chars (bytes) on the stack, and 'a' points to the first char.

When you declare a pointer such as 'char *a', it doesn't point to anything valid initially. You cannot assign anything to '*a' until it references something valid.

What you could do is something like:

char aa[100];
char *a = aa;

*a = '\0';

(I made a similar mistake myself when I was started learning C, and got seg faults too).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top