0

I have tried to return a char* from a function which forms a string by taking parts of two strings given to it. That string must be returned as char*. But when i run the following code, no output is printed. Please help to fix this.

#include <iostream>
#include<string.h>
using namespace std;

char *findpass(char *s1, char*s2)
{
    int sl1 = strlen(s1);
    int sl2 = strlen(s2);
    int i = 0, in = 0;
    char temp[100];
    char *t;
    if (sl1 % 3 == 0)
    {
        for (i = 0; i<sl1 / 3; i++)
        {
            temp[in] = *(s1 + i);
            in++;
        }
    }
    t = temp;
    return t;
}

int main()
{
    char i1[10], i2[10];
    char *f1, *f2;
    cin >> i1 >> i2;
    f1 = i1;
    f2 = i2;
    char *f = findpass(f1, f2);
    cout << f;
    return 0;
}
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37
VicKy
  • 43
  • 6

2 Answers2

2

Your char temp[100]; is local variable it will be destroyed after leaving scope, so t = temp; will point on a mess data. You need to allocate memory for char *temp = new char[100]; Then point t on temp t = temp;. Also you could just return temp;. But after that don forget to deallocate allocated memory by delete []. Look at this example:

char *findpass(char *s1,char*s2)
{
    int sl1=strlen(s1);
    int sl2=strlen(s2);
    int i=0,in=0;
    char *temp = new char[100];
    char *t;
    if(sl1%3==0)
    {
        for(i=0;i<sl1/3;i++)
        {
            temp[in]=*(s1+i);
            in++;
        }
    }
    t=temp;
    return t;
}

And when call this with test input data we have:

int main()
{
    char temps1[] = "123456789";
    char temps2[] = "abc";

    char* retVal = findpass(temps1, temps2);
    std::cout << retVal <<std::endl; // prints 123

    //Deallocate allocated memory before
    delete [] retVal;

    return 0;
}

Output is:

123
Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15
0
#include <iostream>
#include <cstring>
using namespace std;
char *findpass(char *s1,char*s2)
{
    int sl1=strlen(s1);
    int sl2=strlen(s2);
    int i=0,in=0;
    char temp[100];

    if(sl1%3==0)
    {
        for(i=0;i<sl1/3;i++)
        {
            temp[in]=*(s1+i);
            in++;
        }
    }
    cout<<temp<<endl;
    char *t= new char [strlen(temp)+1]; // added dynamic memory allocation
    strcpy(t,temp); // copy temp to t;

    return t;
}

Dynamic memory allocation need to be used to return char* from a function;

int main()
{
   char i1[10],i2[10];
   char *f1,*f2;
   cin>>i1;
   cin>>i2;
   f1=i1;
   f2=i2;
   char *f = findpass(f1,f2);
   cout<<f;
   delete []f;  // delete dynamic memory allocation to avoid memory leak
   return 0;
}
HarshGiri
  • 408
  • 2
  • 12