I can not print the string array on the screen

4
#include <iostream>
#include <string>

using namespace std;
const int NUM = 3;

void hola(string &mana[])
{

    mana[0] = "Hola soy sergio";
    mana[1] = "Mamam me quierre";
    mana[2] = "Hola como estas";
}


int main()
{

    string mana[NUM];

    hola(mana);
    string *p = mana;


    for (int i = 0; i < NUM; i++)
    {
        cout << *p++ << endl; 
    }

    return 0;
}

In this code I want to print with the pointer the 3 sentences per screen but for some reason I get an error where it says that I have not defined my array within the function, but I send it as a reference parameter and still not Accept my array.

What is my problem in this code? Thank you very much for your help.?

    
asked by Mucacran 09.03.2017 в 01:23
source

2 answers

4
  

I send it as a reference parameter and even then it does not accept my array.

You have not guessed with the array reference syntax (array), your code:

string &mana[]

It means " Array of references to objects string ", which will not compile because C ++ does not allow fixes of references. If what you wanted was a reference to fix objects string the correct syntax is:

string (&mana)[]

But this is not allowed in C ++ either. It is mandatory to indicate the size of the array in the references to arrays of objects, so the correct syntax would be:

string (&mana)[NUM]

This will work as long as NUM is a calculable value at runtime. With the right changes, your code compiles without errors and runs flawlessly, you can see it here :

using namespace std;
const int NUM = 3;

void hola(string (&mana)[NUM])
{
    mana[0] = "Hola soy sergio";
    mana[1] = "Mamam me quierre";
    mana[2] = "Hola como estas";
}
    
answered by 09.03.2017 в 09:01
2

The problem is in:

void hola(string &mana[])

Because you are passing a pointer hola(mana); , you must declare a parameter in the pointer to string function:

void hola(string mana[])

Which is to use fix notation, and that is equivalent to:

void hola(string *mana)

In pointer notation.

Additionally, you can also define the function with pointer notation and not fixes:

void hola(string *mana)
{
    *(mana+0) = "Hola soy sergio";
    *(mana+1) = "Mamam me quierre";
    *(mana+2) = "Hola como estas";
}

And the output is still:

  

Hi, I'm sergio
  Mamam wanted me
  Hello, how are you?

    
answered by 09.03.2017 в 04:04