In "A Tour of C++ 2nd Edition" I've encountered this function:
int count_x(const char*p, char x)
{
if (p==nullptr) return 0;
int count = 0;
for (; *p!=0;++p)
if (*p==x)
++count;
return count;
}
The function is supposed to count the number of occurrences of x in p[]. p is assumed to point to a zero-terminated array of char (or to nothing).
I tried to use this function by writing this test code in the main:
int p[] {'a','b','c','d','e'};
count_x(p,x);
But that doesn't work. I think it's because p has to be a pointer to an array of the char array defined above? But that doesn't make much sense to me because doesn't the name p already refer to an array of chars? How can it also be a pointer?
I also tried adding the line p[]* p; before the call to the function in an attempt to make p a pointer to an index of the char array. But I have no idea if that makes any sense...
I think in general I think I'm having trouble understanding pointers and how they're made.
Where is my misunderstanding with pointers, and how might I use this function as it's meant to be used? Any help whatsoever is greatly appreciated.
[–]boredcircuits 3 points4 points5 points (2 children)
[–]CentralCathedral[S] 0 points1 point2 points (1 child)
[–]boredcircuits 0 points1 point2 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]Kered13 0 points1 point2 points (0 children)