samedi 24 septembre 2016

If statement failing to activate

I'm trying to create a function that is supposed to do the following:

-Take in two character arrays, one smaller than the other and determine whether the smaller character array is a subset of the larger array. As an example: Array A: {"s","c","h","o","o","l"} ; Array B: {"c","h"}. I'm obligated to use pointer increment/decrement operations. This is the code that I've produced:

int locator(char *Bigptr, char *Smallptr) {
int count = 0;
    for (; *Bigptr != '\0'; Bigptr++) {
        if (*Smallptr == *Bigptr) {
            for (; (*Smallptr == *Bigptr) != '\0'; Smallptr++, Bigptr++) {}
            if (*Smallptr == '\0') {
                return count;
            }
            else {
                cout << "small is not the subset of big" << endl;
                return 0;
            }
        }
        count++;
    }
return 0; 

This is how I perceive the code should run:

Two pointers to a char array are taken as parameters to the function 'locator'. The variable count is one I've placed in order to tell me what the subscript of the first character in the occurrence in A is (e.g. "school" and "ch" would be element 1 so A[1]). The first for loop ensures that the first value of the larger array is an actual character. The if statement returns true when it founds a character in common. The second for loop then checks to see if all of the smaller array is present in the larger array. When my program compiles, all of this works as expected. The problem appears with the nested if statement. I expected it to be true if, in fact, the smaller array is a subset of the larger one. Why isn't that the case? Take the example of "school" and "ch". the *Smallptr initially points to the first element of Array B (i.e. "ch"), so "c". it then is compared to "c" in "school". The two pointers are then incremented so that they both point to "h" in their respective arrays. Again, they are incremented again so that *Bigptr points to "o" and *Smallptr points to '\0'. Is that not the case? Why does the function always output the else statement?

Aucun commentaire:

Enregistrer un commentaire