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 :)
– user83187
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!
– RHER WOLF
no mind bro...
– user83187