I'm reading a book on C++ (A tour of C++, by Bjarne Stroustrup, second edition) and there is an example of code:
int count_x(char* p,char x)
{
if (p==nullptr) return 0;
int count = 0;
for(;*p!=0;++p)
if (*p==x)
++count;
return count;
}
In this book, it is explained that the pointer p of the function have to point to an array of char (i.e a string ?).
So I tried this code in main:
string a = "Pouet";
string* p = &a;
int count = count_x(p, a);
But count_x needs char not string so It does not compile. So I tried:
char a[5] {'P','o','u','e','t'};
char* p = &a;
int count = count_x(p, a);
But of course it won't work since the pointer alone can't point to a full array. So, lastly I tried to make an array of pointer:
char a[5] {'P','o','u','e','t'};
char* p[5] {&a[0],&a[1],&a[2],&a[3],&a[4]};
int count = count_x(p, a);
But the function wouldn't accept arrays since it wasn't only a char
.
So, I have no idea on how to use the count_x function (which is supposed count the number of x
in p
.
Could you please give me an example of working code which uses this function?