简体   繁体   中英

How to pass char[ ] as call by reference in function

I want to pass a char[] as reference or pointer to a function which modifies the array.

void GetName(char* name[],int* size)
{
    char arr[5] = { 'a','b','c','d' };
    for (int i = 0; i < 4; i++)
        *name[i] = arr[i];
    *size = 4;
}

int main()
{
   char array[10];
   int size=NULL

   GetName(&array,&size);

   cout<<"Length of Name:"<<size<<endl;
   cout<<"Name:"
   for(int i=0;i<size;i++)
    {cout<<array[i];}

   return 0;
}

The above code is not correct. How do I make this work. Edit:

This code modifies the argument passed to the function

The way to modify an array is to pass a pointer to the first element of the array, using the fact that arrays decay to pointers

void GetName(char* name,int* size)
{
    char arr[4] = { 'a','b','c','d' };
    for (int i = 0; i < 4; i++)
        name[i] = arr[i];
    *size = 4;
}

int main()
{
    char array[10];
    int size;
    GetName(array,&size);
    ...
}

In C++ you should use a std::string instead, which is much more straightforward than an array. For instance

#include <string>

std::string GetName()
{
    char arr[4] = { 'a','b','c','d' };
    std::string name;
    for (int i = 0; i < 4; i++)
        name += arr[i];
    return name;
}

int main()
{
   std::string array;

   array = GetName();

   cout<<"Length of Name:"<<array.size()<<endl;
   cout<<"Name:"<<array<<endl;
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM