0

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

MyCopy
  • 155
  • 1
  • 8
  • 4
    Use `std::string` unless this is a programming exercise. – Richard Critten Jun 11 '20 at 09:37
  • `char[]` _is_ a pointer or at least [decays to a pointer](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). – Lukas-T Jun 11 '20 at 09:38
  • Does this answer your question? [Passing an array by reference](https://stackoverflow.com/questions/5724171/passing-an-array-by-reference) – Lukas-T Jun 11 '20 at 09:40

1 Answers1

0

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;
}
john
  • 85,011
  • 4
  • 57
  • 81
  • You don't need the for loop. `std::string` accepts a range in the constructor: `std::string name(std::begin(arr), std::end(arr));`. – Jorge Bellon Jun 11 '20 at 09:46
  • Your code is actually passing the array address directly. This is certainly equivalent to passing the address of the first element, but that's not what's written in your code. – user207421 Jun 11 '20 at 09:50
  • @JorgeBellon I know, I was just trying to do something that was recognisably similar to the OP's code. Clearly the GetName function is not really necessary, since it does nothing more than return a fixed value. – john Jun 11 '20 at 09:56
  • @MarquisofLorne Where do I claim that I'm passing the array address? Where does the OP ask for the array address to be passed? – john Jun 11 '20 at 09:58
  • @here is just an example, in the actual code GetName would return different names and sizes at different times – MyCopy Jun 11 '20 at 10:47