0

I'm a beginner in C++

I been trying to make a function that prints out all the elements within a 2D array, but I can't get this work, and I need some help.

It appears to me that my printArray function can't take 2D array as a valid input data. Can anyone throw me an advice? Also, would there be a better way to build a multidimensional string array without using std::string?

Thanks for your help!

int main ()
{
    
    std::string faces[5] = { "Pig", "sex", "John", "Marie", "Errol"};
    printArray(faces);

    std::string TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    //print2DArray(TwoD);
    
    std::cin.get();
    
}

void print2DArray(std::string x[])
{
    
    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
                    std::cout << x[i][j] << std::endl;
        
        }
    
}
MikeCAT
  • 61,086
  • 10
  • 41
  • 58
Rain Rise
  • 31
  • 1
  • 6
  • Whenever you use a POA (Plain Old Array), you need to pass the number of elements in the array as a parameter along with a pointer (or reference in C++) so the function knows how many elements there are. Instead suggest `std::vector` so you can pass a reference to the vector and use the `.size()` member function to determine the number of strings (elements) in the vector. – David C. Rankin Dec 06 '20 at 06:18
  • Fair duplicate, but see answer by *Legends2k* (some of the other answers are downright questionable) – David C. Rankin Dec 06 '20 at 06:21
  • @DavidC.Rankin Yeah, it might need a modern answer. Might be worth adding one, or even placing a bounty. –  Dec 06 '20 at 06:33

1 Answers1

2

You have to use proper type (matched with data to be passed) for function arguments.

Also you have to declare or define functions before using them.

#include <iostream>
#include <string>

void print2DArray(std::string x[][2]); // declare function

int main ()
{
    std::string TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    print2DArray(TwoD);
}

void print2DArray(std::string x[][2])
{

    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
            std::cout << x[i][j] << std::endl;
        
        }

}

Using const char* may be a good way to build a multidimensional string array without using std::string if you are not going to modify the strings.

#include <iostream>

void print2DArray(const char* x[][2]); // declare function

int main ()
{
    const char* TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    print2DArray(TwoD);
}

void print2DArray(const char* x[][2])
{

    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
            std::cout << x[i][j] << std::endl;
        
        }

}
MikeCAT
  • 61,086
  • 10
  • 41
  • 58