The program is expected to print each char of the string array.
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char* numbers[10]{"One", "Too", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Zero"};
/* This version did not work. Why?
for (const char** ptr = numbers; *ptr != nullptr; *ptr++) {
const char* pos = *ptr;
while (*pos != '\0')
cout << *(pos++) << " ";
}
*/
for(unsigned int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); ++i)
{
const char* pos = numbers[i];
while(*pos != '\0')
printf("%c ", *(pos++));
printf("\n");
}
return 0;
}
I am aware that my code is a mixture of C++17 and C(in a transition from C to C++, nullptr
, cout
are two examples), but not sure the first for-loop
with
for (const char** ptr = numbers; *ptr != nullptr; *ptr++)
is correct or not. What's wrong with it? Is there a "best practice" to looping thru array of string(char array , not string object yet), especially with the double pointer I'd like to catch, in this case? Thanks!