Here goes my code:
#include <iostream>
using namespace std;
int countX(char*, char);
int main() {
char msg[] = "there are four a's in this sentence a a";
//char *ptr = msg; // <----- question 2!
cout << countX(msg, 'a');
cin.get();
}
int countX(char* ptr, char x) {
int c = 0;
for (; *ptr; ptr++) {
if (*ptr == x) c++;
}
/*
while(*ptr) {
if(*ptr==x) c++;
ptr++;
}
*/
return c;
}
I was wondering a few things specifically regarding safe practice and pointers:
- My conditional statement in the for-loop
; *ptr ;
, is this safe practice? Will it every break if there happens to be something stored in the memory address right next to the last element in the array? Is that even possible? How does it know when to terminate? When is*ptr
deemed unacceptable? - (concerning the commented out
char *ptr = msg;
in the main): I understand a pointer and an array are very similar, however, is there a difference between passing the actual array tocountX
vs. passing a pointer (which points to the beginning of the array?). - In
countX
I've provided two different ways to approach the simple problem. Is one considered superior over the other?