Click here to Skip to main content
15,922,325 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int n;
    char* element[] = "Hydrogen" ,"Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon" };
    n=strlen(element);
    printf("%d",n);
    return 0;
}


What I have tried:

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

int main()
{
    int n;
    char* element[] = {"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon"};
    n=strlen(element);
    printf("%d",n);
    return 0;
}
Posted
Updated 25-Mar-17 3:38am
Comments
Garth J Lancaster 25-Mar-17 2:08am    
I suspect I know the answer, but, for completeness, do you wish to know how many elements are in the element array, for which 10 would be correct, vs the size (number of characters) of the first element

obviously, the issue in your code, is that

n=strlen(element);

isnt doing quite what you expect/think its doing ....

[edit]
I'll toss this out there for you to think about - have you looked at the sizeof() function ?
have a look at sizeof(element) and sizeof(element[0])
[/edit]

If you look at the definition of strlen: strlen - C++ Reference[^] it takes a parameter which is a pointer to a char - or a string in other words - and returns the number of characters up to the first null value.
That isn't what to are passing it: element is an array of pointers to char -or an array of strings. So it looks at the array as if it was a string, and gets it horribly wrong.

Pass it one of the elements of the array, and it'll return what you want!
n=strlen(element[0]);
Or
n=strlen(element[1]);
...
 
Share this answer
 
The size of an array is known at compile time. Usually a macro like the following is used
C++
#define NELEM(a)  (sizeof(a) / sizeof(a[0]))

Try, for instance
C
#include <stdio.h>

#define NELEM(a)  (sizeof(a) / sizeof(a[0]))

int main()
{
    int n;
    char* element[] = { "Hydrogen" ,"Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon" };
    n = NELEM(element);
    printf("%d\n",n);
    return 0;
}
 
Share this answer
 
We can not use strlen to get the count of elements in an array.

I have solved for you and linked as below.

length of an array of strings[^]
 
Share this answer
 
v3
Comments
Richard MacCutchan 25-Mar-17 9:43am    
If you know the answer then post the code here, not on another website.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900