【问题标题】:Returning char* from a function [duplicate]从函数返回 char* [重复]
【发布时间】:2018-10-18 03:20:23
【问题描述】:

我试图从一个函数中返回一个 char*,该函数通过取给它的两个字符串的一部分来形成一个字符串。该字符串必须以 char* 形式返回。但是当我运行以下代码时,不会打印任何输出。请帮助解决此问题。

#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;
}

【问题讨论】:

  • 你必须将内存(malloc)分配给指针t
  • tempfindpass() 的本地对象
  • 我试过malloc,还是不行:t=(char*)malloc(10);
  • 不使用char *s,而是使用std::string,您可以按值返回

标签: c++ char


【解决方案1】:

你的char temp[100];是局部变量,离开作用域后会被销毁,所以t = temp;会指向一个乱七八糟的数据。 您需要为char *temp = new char[100]; 分配内存,然后将t 指向临时t = temp;。你也可以return temp;。但在那之后不要忘记通过delete [] 释放分配的内存。看这个例子:

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;
}

当使用测试输入数据调用它时,我们有:

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;
}

输出是:

123

【讨论】:

  • "123456789" 是一个const char *,不能绑定到char *
  • @HiI'mFrogatto 谢谢你的评论,你是对的,在我的回答中修正了它。
  • 成功了.. @Alexey_Usachov
【解决方案2】:
#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;
}

需要使用动态内存分配来从函数中返回 char*;

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;
}

【讨论】:

  • strlen + 1. 尾随\0
  • @HiI'mFrogatto 是的,更改完成
猜你喜欢
  • 2020-02-21
  • 2013-01-03
  • 2018-05-09
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
相关资源
最近更新 更多