繁体   English   中英

无法从 function c++ 返回数组

[英]having trouble returning an array from a function c++

#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;

void getinput (string &first,string &second);
void lengthcheck (string first, string second);
//int anagramcheck (string word);
int* lettercounter (string input);

int main()
{
    std::string a;
    std::string b;
    getinput(a,b);
    lengthcheck (a,b);
    lettercounter(a);
    lettercounter(b);

    int* one = lettercounter(a);
    int* two = lettercounter(b);

    if (one == two)
        cout << "You Have Entered An Anagram" << endl;
    else
        cout << "You Have Not Entered An Anagram" << endl;
}

void getinput (string &first, string &second) {
    cout << "Enter First Input: ";
    getline(cin, first, '\n');
    cout << "Enter Second Input: ";
    getline(cin, second, '\n');
    cout << "You Entered " << first << " and " << second <<endl;
}

void lengthcheck(string first, string second){
    int lengtha = first.length();
    int lengthb = second.length();
    
    if ((lengthb > 60) || (lengtha > 60)) {
        cout << "Input Is Invalid" << endl;
    } else if (lengtha !=lengthb) {
        cout << "Input is not an anagram" << endl;
    } else {
        cout << "Input is Valid" << endl;
    }
}

int* lettercounter(string input)
{
    static int freq[26] = {0};
    int length = input.length();
    for (int i=0; i<26; i++) {
        freq[i]=0;
    }
    
    for (int i=0; i <length; i++) {
        if(input[i]>='a' && input[i]<='z')
        {
            freq[input[i] - 97]++;
        }
        else if(input[i]>='A' && input[i]<='Z')
        {
            freq[input[i] - 65]++;
        }
    }
    
    for(int i=0; i<26; i++) {
        /* If current character exists in given string */
        if(freq[i] != 0)
        {
           printf("'%c' = %d\n", (i + 97), freq[i]);
        }
        return freq;
    }
}

我无法从名为lettercount的用户定义的 function 返回名为freq的数组。 有人可以给我提示吗? 我需要lettercount来返回一个数组。 我需要调用 function lettercount 两次,以便我可以比较每个数组的结果以确定两个输入是否是字谜。 我不确定 function 是否向 main 返回实际值。

首先, freq不应该是 static。通过将其设为 static,您每次都会访问同一个数组。 对于您想做的事情,您不想总是访问相同的 memory。

其次,你不能只返回一个指向 memory 的指针,它没有被动态分配或者不是 static。当你离开 scope 时(即你从 function lettercounter返回main ),memory 被占用该阵列将被释放。 因此,您将返回一个指向不再保留的 memory 的指针,从而导致未定义的行为。

如果您确实需要使用原始指针,那么每次输入lettercounter时,您都需要像这样动态地为数组分配 memory: int * freq = new int[26]; . 这将为大小为 26 的数组保留 memory。然后,当您返回 freq 时,memory 仍将被分配。 但是,不要忘记分配给new的 memory 不会删除自身。 你必须清理你的烂摊子。 在这种情况下,在main的末尾你会调用delete[] one; delete[] two; .

int* lettercounter(string input)
{
  int * freq = new int[26];
    .
    .
    .
  return freq;
}

int main()
{
  .
  .
  int* one = lettercounter(a);
  int* two = lettercounter(b);
  .
  .
  delete[] one;
  delete[] two;
}

无论如何,我建议您学习使用智能指针标准容器(如vector )。 这些操作会简单得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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