Home > Software engineering >  Why can't my conditional detect an empty char?
Why can't my conditional detect an empty char?

Time:05-23

I'm trying to create "String Array Count" function. How does it it work? The loop is going to stop if the char is empty, then the length is going to show. The error is, empty char conditional didn't detect empty char. The result is infinite while loop.

Edit : I want the result of my function is 3

#include <stdio.h>

#define s 1000
int strarrlen(char str[s][s]){
    int i, len = 0;
    while (1){
        if(str && !str[i]){
            break;
        } else {
            len  = 1;
        }
        i  ;
    }
    return len;
}

int main(){
    char words[s][s] = {"First", "Second", "Third"};
    printf("words array total is %i", strarrlen(words));
}

CodePudding user response:

Here you are using a true 2D array. That means that you have s (1000) arrays of s characters. As you initialize it, the C language ensures that all unused chars are 0.

It means that the first unused slot will the the first one where the first character is 0. So your code should be:

#include <stdio.h>

#define s 1000
int strarrlen(char str[s][s]){
    int i=0, len = 0;     // do not forget to initialize i
    while (1){
        if(str && !str[i][0]){  // str[i] is the address of the i-th array
            break;
        } else {
            len  = 1;
        }
        i  ;
    }
    return len;
}

int main(){
    char words[s][s] = {"First", "Second", "Third"};
    printf("words array total is %i", strarrlen(words));
}

That being said, 2D arrays are often used in numeric computation, but seldom for handling strings. A much more common way is to use arrays of pointers with a NULL delimiter: char words[1000][1000] uses 1000000 characters in memory but char *words[] = {"First", "Second", "Third", NULL}; only needs 19 characters and 4 pointers, so 36 bytes on a 32 bits architecture and 51 bytes on a 64 bits one.

But here you test for pointer nullity:

#include <stdio.h>

int strptrlen(char **str) {
    int i = 0, len = 0;
    while (1) {
        if (str && !str[i]) {
            break;
        }
        else {
            len  = 1;
        }
        i  ;
    }
    return len;
}

int main() {
    char *words[] = { "First", "Second", "Third", NULL };
    printf("words array total is %i", strptrlen(words));
}

CodePudding user response:

Arrays in C don't have any metadata, how do you expect to find the end if you don't make a marker for it. Usually with arrays or pointers you use NULL as a stop value.

#include <stdio.h>

//You don't need to hardcode your array size with pointers, just check for nullity
int strarrlen(char **str){
    int i, len = 0;
    
    if (str == NULL) {
        return 0;
    }
    while (str[i] != NULL){
        i  ;
    }
    return i;
}

int main(){
    char words[s][s] = {"First", "Second", "Third", NULL};
    printf("words array total is %i", strarrlen(words));
}
  • Related