Hello, you can do this in two ways.
The first is to use vector notation within the function parameters:
mostrarMensagem(char msg[])
{
cout << msg;
}
mostrarMensagem("oi");
In this case the function shows Remember takes as argument a char array, no matter the size of the array.
The second way is using pointer notation:
mostrarMensagem(char * msg)
{
cout << msg;
}
mostrarMensagem("oi");
In these two cases the function shows Remember expects as argument a pointer to a char, because when you use char msg[]
as function parameter is equivalent to use char * msg
.
Since the char pointer received by the function stores the memory address of the first "string" character, the other characters will be in the memory positions subsequent to that pointer up to a limit that is the size of the "string", we can use pointer arithmetic to display the entire array starting from position *(msg + 0)
while *(msg + i) != '\0'
indicating the end of the "string":
mostrarMensagem(char * msg)
{
int i = 0;
while(*(msg + i) != '\0') {
cout << *(msg + i);
i++;
}
}
mostrarMensagem("ola156186485348545215554548843456etc");
similarly, we can use the array notation that we are most used to, which in this case will give in the same:
mostrarMensagem(char * msg)
{
int i = 0;
while(msg[i] != '\0') {
cout << msg[i];
i++;
}
}
mostrarMensagem("ola156186485348545215554548843456etc");
Very good, thank you.
– PerduGames