Given an array of strings, i need to find out the number of strings in it.
I followed this
but this doesn't work if i am passing this into a function.
here's the code i tried
#include<string>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int f1(char* input1[])
{
string s="";
cout<<sizeof(input1)<<endl; //print 4
cout<<sizeof(char*)<<endl; //print 4
int l=sizeof(input1) / sizeof(char*);
//giving l=1 here but should be 8
}
int main()
{
char *str2[]={"baba","sf","dfvf","fbfebgergrg","afvdfvfv","we","kkhhff","L"};
int l=sizeof(str2) / sizeof(char*);
cout<<l<<endl; //print 8
cout<<sizeof(str2)<<endl; //print 32
cout<<sizeof(char*)<<endl; //print 4
f1(str2);
}
The simple method to find the number of objects in an array is to take the size of the array divided by the size of one of its elements. Use the sizeof operator which returns the object's size in bytes.
Algorithm : Step 1– Traverse matrix character by character and take one character as string start. Step 2– For each character find the string in all the four directions recursively. Step 3– If a string found, we increase the count.
A string is a 1-dimensional array of characters and an array of strings is a 2-dimensional array of characters.
The 2-Dimensional arrays are organized as matrices which can be represented as the collection of rows and columns as array[M][N] where M is the number of rows and N is the number of columns.
sizeof(char*)
gives you the size of the char*
pointer (which is 4 on your system).
sizeof(str2)
is giving you the size of the array str2
. There are 8 elements, each one is a pointer type. So the total size on your system is 8 x 4 = 32.
To get the length of a string, use strlen
.
Do consider std::vector<std::string>>
as an alternative in C++.
You can not know the length of an array if you only have a pointer to it. And you do have only a pointer because you cannot pass arrays by value. Arrays passed to a function will automatically decay to a pointer and the argument type char* foo[]
is equivalent to char** foo
. size_of
doesn't help because it will only tell the size of the pointer itself.
Pass the length as an argument to f1
. Or better yet, use std::vector
or std::array
.
i cannot modify the given function prototype
Well, that's unfortunate. Then you must resort to some trickery. The simplest workaround is to store the length in a global variable instead of a function parameter.
Another possibility is a terminating value For example, always end the array with nullptr and never allow other elements to have that value. In the same way as c-strings are terminated with null character. Then you can stop iterating the array when come across nullptr. But I assume you cannot modify the array either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With