Search code examples
c++arraysstring-literals

How to pass character array to a function in C++ without any temporary char array as variable?


I have the following code

void func(char c[])  {
    c[1]= '@';
    std::cout<<c<<"\n"
             <<sizeof(c)<<"\n";
}

// Main 1
int main()  {
    char temp[6] = "pinta";
    func(temp);
}

Here if I change the main function to the following

//Main 2
int main()
{
    func("pinta");
}

meow@vikkyhacks ~/Arena/c/LinkedList $ g++-4.8 scrap/test.cpp 
scrap/test.cpp: In function ‘int main()’:
scrap/test.cpp:12:14: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  func("pinta");
              ^

After some googling, I learned that the second main is not passing any character array by instead passing a read only string literal which when hits the c[1] = '@' throws a seg fault.

My Question is

  1. "How do I avoid the use of the temp variable which is used in the Main 1 and directly pass a character array to the func as its parameter ?"

  2. And important condition is to allow the editing of the character array passed into the func.

EDIT

I see there are many answers which prevent me from doing c[1]= '@'; , which I cannot do because that line is very important for me.


Solution

  • You cannot avoid creating a temporary, because it's illegal to write to the memory of a string literal, but you can make the compiler create it for you. Take as your parameter std::string instead- this is much safer than char arrays and will create a copy for you.