I have an really simple example of array of const char’s and one function supposed to print them out (iterate through the chosen one). Contrary all my expectations, it’s iterating through all of them and not only the one that was passed as argument.
#include <iostream>
const char* oranges[] = {
"ORANGE",
"RED ORANGE"
};
const char* apples[] = {
"APPLE"
};
const char* lemons[] = {
"LEMON"
};
void printFruit(const char** fruit){
int i =0;
while (fruit[i] != '\0'){
std::cout << "---------------------\n";
std::cout << fruit[i] << "\n";
i++;
}
}
int main (int argc, const char * argv[])
{
printFruit(oranges);
return 0;
}
The result i would expect is that the function printFruit with oranges given as argument will print ORANGE and RED ORANGE, meanwhile i get printed ALL of the fruits defined (from other arrays), like this:
---------------------
ORANGE
---------------------
RED ORANGE
---------------------
APPLE
---------------------
LEMON
Sorry for my ignorance but why is this happening ?
Edit: I followed this question: defining and iterating through array of strings in c that is similar to mine.
You are checking that
fruit[i] != '\0'. That is wrong becausefruit[i]is achar *, not a char. Furthermore, your vectors aren’t terminated. You probably wanted to check whetherfruit[i] != 0, or*fruit[i] != '\0'. In the first case, you need to terminate the vectors like this:In the second: