Problems with function that returns character array in C++

Asked

Viewed 1,485 times

1

Follows the code:

#include <iostream>

char* criaVetor(){

     char vetor[20]="Olá mundo!";
     return vetor;
}

int main(){

    char retorno[20]=criaVetor;

    std::cout << retorno;

    return 0;
}

error: array must be initialized with a Brace-Enclosed initializer

I didn’t understand very well, what I have to do to get around this mistake?

2 answers

3

There are some problems in this code, what is being shown is that it is calling the function without the parentheses. Calling criaVetor() this error disappears.

Only there’s actually another error, you’re creating a local vector (stack) within this function and returning it, the problem is that the moment the function ends this vector is destroyed then you are returning something that cannot be accessed.

One possible solution is to allocate heap, then the contents are not destroyed. Although this is not ideal, the most correct is to allocate the memory where it will be used and pass a pointer of this allocation, which can usually be local even and then the function uses this storage location, so you better manage life time and run fewer risks of having memory leak. In C it is customary to use malloc(), in C++ it is customary to use the operator new.

But there is another problem, you are using C++ and trying to use a character array. This is not recommended, use a string and forget all these difficulties. That is, in C++ program in C++, not in C. Something like this:

#include <iostream>
#include <string>
using namespace std;

string criaString() {
    return "Olá mundo!";
}

int main(){
    string retorno = criaString(); //esta variável nem é necessária
    std::cout << retorno;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

0


Leonardo, it seems that in a good part you are confusing things from one language to another. I will explain to you the mistakes I found.

char retorno[20] = criaVetor ;

First, function call has parentheses, always, even without arguments.

char retorno[20] = criaVetor() ;

Second, to initialize a chars vector citing the values of the elements one must use "Olá mundo!" or {'O','l','á',' ','m','u','n,'d','o','!','\0'}. No function can return this.

In this case, the function returns a pointer to char, so with it you can only initialize a pointer to char, not twenty array elements. The retorno is treated as a constant pointer, so it cannot be assigned or initialized.

char *retorno = criaVetor() ;

If you want an array of twenty elements to have the value of cells in the returned pointer, you will have to copy these values one by one. For this, you can use the function std::string::copy of the string library (#include <string>).

Third, in the function you return the pointer that points to cells that only exist during the execution of the function (allocated locally in the execution stack). To the function finalda, the cells in that pointer no longer exist, which gives risk of bug.

char* criaVetor(){
     char vetor[20] = "Olá mundo!";
     return vetor;
}

There are three solutions and I think in the quickest case is to give a prolonged life time to the cells of this function using keyword static. Keyword static in a local variable, it will have the same life time as the program, that is, it will exist even after finishing executing the function and in the next call will have the same value as it had the last time.

char* criaVetor(){
     static char vetor[20] = "Olá mundo!";
     return vetor ;
}

Another way is to allocate the array of 20 elements using keyword new, then assign the cell values with the string (for this you can copy using the function std::string::copy cited above) and returns. But the problem is that you will have to control the existence of it, using delete when you no longer need it.

There is one more option (I think more appropriate), which is the "no use of pointers for char" but rather the string class (it’s in the string library, which I just quoted), which there controls all these questions involving pointers, allocations, etc. Pointers to char is more C language than C++, whereas string class is C++ and exists exactly to facilitate your life. Use pointers only if necessary.

Any doubt?

  • This part of me not putting the parentheses was error when posting the code, but otherwise...thanks for responding :)

  • Beauty. Weird... I gave the most complete, clearest answer and everything, it was even marked as the solution and, even so, has final balance of 2 votes against!

  • no mind bro...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.