Home > database >  How to find length of particular string in array of pointer to string?
How to find length of particular string in array of pointer to string?

Time:11-27

How to find lenth of stringfrom array of pointer to string. For example if i want to find length of string "apple" then how can i calculate length of it. I tried many way but i couldnt , if i do sizeof(str[0]) it returns size of pointer (4 byte in my 32-bit device) , and i want to know if they are stored in memory location next to each other or not?

const char *str[] = {
        "apple", "ball", "cat", "dog", "mep", "helsdf"
    };

CodePudding user response:

Use strlen() from string.h

#include <stdio.h>
#include <string.h>

int main() {
    const char *str[] = {
        "apple", "ball", "cat", "dog", "mep", "helsdf"
    };

    printf("Length of \"%s\": %zu\n", str[0], strlen(str[0]));

    return 0;
}

CodePudding user response:

... and i want to know if they are stored in memory location next to each other or not?

To check that you need to look at pointer values and to do some pointer arithmetic.

Like:

// Print the location of each substring
for (size_t i = 0; i < (sizeof str / sizeof str[0]);   i)
{
        printf("%p : %s\n", (void*)str[i], str[i]);
}

// Check if str[i 1] is located just after str[i]
for (size_t i = 0; i < (sizeof str / sizeof str[0] - 1);   i)
{
    if ( (str[i]   strlen(str[i])   1) == str[i 1] )
    {
        printf("%s is stored just after %s\n", str[i 1], str[i]);
    }
}

Possible output:

0x558cfd6e5004 : apple
0x558cfd6e500a : ball
0x558cfd6e500f : cat
0x558cfd6e5013 : dog
0x558cfd6e5017 : mep
0x558cfd6e501b : helsdf
ball is stored just after apple
cat is stored just after ball
dog is stored just after cat
mep is stored just after dog
helsdf is stored just after mep

Remember that the result of the above code may change every time you compile your source code.

CodePudding user response:

warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat] printf("Length of "%s": %d\n", str[0], strlen(str[0])); ~~ ^~~~~~~~~~~~~~ %lu

  • Related