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

Length of array of strings

How can we determine the length of an array of strings when we don’t know the length?

For example in this piece of code:

#include <stdio.h>

int main() {
    int n;
    char names[3][10] = { “Alex”, “Phillip”, “Collins” };

    for (n = 0; n < 3; n++)    
        printf(“%s \n”, names[n]);
}

n < 3 is assuming you know the length of the array but how can you determine it’s length when we don’t know?

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

I have tried a few alternatives such as:

int arraySize() {
    size_t size, i = 0;
    int count = 0;
    char names[3][10] = { “Alex”, “Phillip”, “Collins” };

    size = sizeof(names) / sizeof(char*);

    for (i = 0; i < size; i++) {
        printf("%d - %s\n", count + 1, *(names + i));
        count++;
    }

    printf("\n");
    printf("The number of strings found are %d\n", count);
    return 0;
}

or

for (n = 0; n < sizeof(names); n++)

but they all error out.

Any help is appreciated.

>Solution :

I am not sure what you mean by they all err out.

There is a syntax issue in the code posted as you use guillemet characters instead of double quotes: “Alex” should be "Alex". This could be a side effect of your cut/paste method to post the code, but nevertheless a potential issue.

Your approach using size = sizeof(names) / sizeof(char*); is right but the type is incorrect: names[0] is not a char *, it is an array of 10 characters. You should use size = sizeof(names) / sizeof(names[0]); which works for all arrays, regardless of the type.

Here is a modified version where the length of the array is determined by the compiler:

#include <stdio.h>

int main() {
    char names[][10] = { "Alex", "Phillip", "Collins" };
    int i, length = sizeof(names) / sizeof(names[0]);

    for (i = 0; i < length; i++)    
        printf("%d: %s\n", i + 1, names[i]);

    return 0;
}

Notes:

  • you could use size_t instead of int for array length and index variables, but it is only necessary for very large arrays and the printf conversion specifier would be %zu for a value of type size_t.

  • it is less confusing to use length for the length of an array and reserve size for sizes in bytes obtained from sizeof().

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