I can not understand where naaportachil. I just started to learn C ++ and the primal is such a task, find the number of the letter "a" in the line that is passed to the function and output the number of these letters. Code means it looks like this.

char str(char *str[]) { int j = 0; for (int i = 0; i < sizeof(str) / sizeof(*str); i++) { if (str[i] == "a") { j++; } } return j; } Вызов функции в main. cout << str("saassssasasasass") << endl; 

So when I call the function, VS gives this error. What is the problem? And another question: why do we need the stars char *str[] and sizeof(str) / sizeof(*str)

enter image description here

  • everything is wrong here. the argument is not a string, but an array of pointers to the string. and sizeof does not consider the length of the string, you need strlen. I recommend to look at the source code of strcmp. Maybe there will be ideas. - Adokenai
  • pointers - VTT

2 answers 2

Error one: pass a string to a function, but accept it as an array of strings.

 char str(char *str[]) { 

it is necessary so:

 char str(char const * str) { 

Error two: you are comparing a letter with a string:

 if (str[i] == "a") { 

it is necessary so:

 if (str[i] == 'a') { 

The code sizeof(str) / sizeof(*str) is someone blurted out something. We wanted to calculate the number of letters depending on the size of the structure and the size of the elements.

 for (int i = 0; i < sizeof(str) / sizeof(*str); i++) { 

for the string you need to:

 for (int i = 0; i < strlen(str); i++) { 
     int str(const char *str) { int count = 0; for(; *str; str++) if (*str == 'a') ++count; return count; }