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?
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.
CodePudding user response:
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 ofint
for array length and index variables, but it is only necessary for very large arrays and theprintf
conversion specifier would be%zu
for a value of typesize_t
.it is less confusing to use
length
for the length of an array and reserve size for sizes in bytes obtained fromsizeof()
.
CodePudding user response:
first every string is ended with a special character '\0' means
{'A','L','E','X','\0'}
even you haven't put '\0' there but compiler put it there for it convenient
int lenght(char *str){
int count = 0 ;
for(int i=0;str[i]!='\0';i ){
count ;
}
return count ;
}
use this function to count your string length like :
int main(){
char names[3][10] = {"Alex", "Phillip", "Collins"};
printf(“%d \n”,lenght(names[1] );
return 0 ;
}