Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to pass the 2 dimension array to a function and the array recieved in the function is just random characters

C++
void SomeFunction(char arr[][50])
{
   //arr is just random strings
}

int main()
{
  char arr[50][50] = { {"Hello"}, {"World"} };
  SomeFunction(arr);
}


What I have tried:

I have tried googling and stuff and did whatever it said and it still doesn't work
Posted
Updated 4-Mar-20 4:10am
v2
Comments
Stefan_Lang 4-Mar-20 10:56am    
I've added this line to SomeFunction() in onlinegdb compiler (https://www.onlinegdb.com/online_c++_compiler):
cout << arr[0] << endl << arr[1] << endl;

This outputs
Hello
World

So what is your question?

C++
char arr[50][50] = { {"Hello"}, {"World"} };

You need to understand that a string is an array of chars.
So your code is a list of list of strings which means a list of list of list of chars.
And a string is a zero terminated list of chars.
Try:
C++
char arr[50][50] = { "Hello", "World" };
 
Share this answer
 
v2
To add to what Patrice T says, try this:
void SomeFunction(char arr[][50])
{
    for (int i = 0; i < 50; i++)
    {
        if (arr[i][0] != '\0')
        {
            cout << arr[i] << "\n";
        }
    }
}

int main()
{
  char arr[50][50] = { {"Hello"}, {"World"} };
  SomeFunction(arr);
  return 0;
}
It'll print just the strings you added when you declared the array.
 
Share this answer
 
Comments
Patrice T 4-Mar-20 10:49am    
Hi OG,
Are you sure about the:
char arr[50][50] = { {"Hello"}, {"World"} };
OriginalGriff 4-Mar-20 10:53am    
Absolutely. It allocates space for 50 strings of 50 characters and populates two of them with copies of the string literals.

It's been a while since I did much with C / C++, so I checked with an online compiler:
https://www.onlinegdb.com/online_c++_compiler
Patrice T 4-Mar-20 11:52am    
OK, I take note of this counter intuitive syntax, another reason to not use C++ :)
Stefan_Lang 4-Mar-20 10:57am    
onlinegdb accepts it just fine: https://www.onlinegdb.com/online_c++_compiler

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900