Frank Tocci
Frank Tocci

Reputation: 634

two strings should be different length but are counted as same length

I'm running into an issue with a pair of strings. Toward the bottom of my first function I test the length of both strings, and even though searchingForLength should be less than half the size of searchedLength, they are the same "length". What is going on here?

Here's the code:

#include <stdio.h>
#include <stdbool.h>

bool findString(const char searched[], const char searchingFor[]) {
    int i, j, k = 0, searchedLength = sizeof(searched)/sizeof(searched[0]), searchingForLength = sizeof(searchingFor)/sizeof(searchingFor[0]);

    bool in = false;

    for (i = 0; i < searchedLength; i++) {
        for (j = 0; j < searchingForLength; j++) {
            if (searched[i] == searchingFor[j]) {
                k++;
                if (k == searchingForLength) {
                    in = true;
                }
            }
        }
    }

    printf("%d\n", k);
    printf("%d\n",searchingForLength);
    printf("%d\n",searchedLength);
    if (in == true) {
        printf("Yes\n");
    }
    else {
        printf("No\n");
    }
    return in;
}

int main (void) {

    const char searched[] = { 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'p', 'i', 'e' };
    const char searchingFor[] = { 'l', 'i', 'k', 'e' };

    findString(searched, searchingFor);

    return 0;
}

Upvotes: 0

Views: 103

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The sizeof is an operator and it gives the size of the type of it's argument, which is not the length of a string.

For arrays it gives the size of the array in bytes, to calculate the length of a string you need strlen(), but none of your arrays are strings, and hence you can't use strlen(), they are not strings in a c string sense.

A string in c, is a sequence of non-nul bytes followed by a nul byte, your arrays don't have a terminating nul, so the str* functions can't handle them properly.

A simple implementation of strlen() would be

size_t strlen(const char *string)
 {
     size_t length;
     length = 0;
     while (*string++ != '\0')
         length++;
     return length;
 }

as you can see, if there is no '\0' or nul byte1 in the data, the function will keep iterating beyond the end of the string, what happens after that is undefined.


1They are the same and their value is 0

Upvotes: 2

Jonatan Hedborg
Jonatan Hedborg

Reputation: 4432

Sizeof is evaluated at compile time, and in this case it will return the size of a pointer (char[] is more or less a char*). You should use strlen instead.

Oh and as it has been mentioned, you strings are not zero-terminated, so that won't really work either. You should define your strings as

const char blah[] = "whee"

Upvotes: 3

Related Questions