Search code examples
c++arrayspointersdynamic-memory-allocation

how to pass array used in function to the dynamically allocated array of main?


#include<iostream>

#include<string>    
using namespace std;

char *fun(const char* a)
{
        int size=strlen(a);

        char* str=new char[12];

        for(int i=0;i<size-1;i++)
        {
                str[i]=a[size-i-1];
        }

        str[size-1]='\0';

        return str;
}

main()
{
        int i=0;

        char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};

        char *p=new char[11];

        p=fun(a);

        for(int i=0;i<11;i++)
        {
                cout<<p[i]<<" ";
        }

        delete(ptr);
}

//having some troubles using array p in the main here please help.


Solution

  • There are many issues:


    Here the a array is not NUL terminated, therefore strlen cannot be used on it in fun:

    char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};
    

    Here you are allocating a fixed size of 12, but you need a dynamic size depending on the length of the string:

    char* str=new char[12];
    

    Then:

    str[size-1]='\0';
    

    should be:

    str[size] = '\0';
    

    otherwise your resulting string will miss the last character.


    In main:

    char *p=new char[11];
    

    is pointless because you assign p right after with p=fun(a);.


    You call delete(ptr);, but there is no ptr.


    And finally you should also #include <string.h> be sure that strlen is defined, but one some platforms it compiles also without #include <string.h>.


    You probably want this:

    #include <iostream>
    #include <string>
    #include <string.h>
    
    using namespace std;
    
    char *fun(const char* a)
    {
      int size = strlen(a);
      char* str = new char[size + 1];
    
      for (int i = 0; i < size; i++)
      {
        str[i] = a[size - i - 1];
      }
    
      str[size] = '\0';
      return str;
    }
    
    int main()
    {
      char a[] = "ABCDE";    
      char *p = fun(a);    
      int size = strlen(p);
    
      for (int i = 0; i < size; i++)
      {
        cout << p[i] << " ";
      }
    
      delete[] p;
    }