C++ Why does a char variable as a function parameter defined with square brackets not need '&' sign? [duplicate]

I have a simple example.

I am changing a variable in a function and then print it outside the function.

For the integer and string, we do need & to "inherit" those changes (passing by reference). But for the char defined like below, we do not.

Why?

#include <iostream>
#include <string>
#include <stdio.h>

void ChangeFunc(std::string &FuncString, char FuncChar[], int &x)
{
    FuncString = 'b';
    FuncChar[0] = 'b';
    x = 2;

    FuncChar[1] = '\0';
}

int main()
{
    std::string LocString = "a";
    char LocChar[2] = {'a','\0'};
    int a = 1;

    ChangeFunc(LocString, LocChar, a);

    std::cout << LocString << std::endl;
    std::cout << LocChar << std::endl;
    std::cout << a << std::endl;
}

Result is b-b-2.

And if we throw away square brackets for the char:

void ChangeFunc(std::string &FuncString, char FuncChar, int &x)
{
    FuncString = 'b';
    FuncChar = 'b';
    x = 2;

    //FuncChar[1] = '\0';
}

int main()
{
    std::string LocString = "a";
    char LocChar = {'a'};
    int a = 1;

    ChangeFunc(LocString, LocChar, a);

    std::cout << LocString << std::endl;
    std::cout << LocChar << std::endl;
    std::cout << a << std::endl;
}

Result is b-a-2.

I've read a lot about pointers, but didn't find the exact reason for this.



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations