Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't my conditional detect an empty char?

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));
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading