将字符串*类型数组从函数返回主函数 我是C++的新手,我正在做一个函数来修改字符串

将字符串*类型数组从函数返回主函数 我是C++的新手,我正在做一个函数来修改字符串,c++,arrays,function,pointers,C++,Arrays,Function,Pointers,它获取一个字符串数组,对它们进行洗牌,然后将它们返回主字符串 我将返回一个指向名为shuffled的字符串数组的指针。我遇到的问题是,当我试图将指向数组的新指针保存到main中的另一个指针时,我开始得到奇怪的值,这些值要么引用我计算机中的文件位置,要么引用一堆数字 我将在这里发布整个代码,但您真正想了解的是返回类型、如何返回以及如何将其保存在main中。请告诉我为什么我的指针没有引用在函数中创建的工作数组。代码如下: #include <cstdio> #include <st

它获取一个字符串数组,对它们进行洗牌,然后将它们返回主字符串

我将返回一个指向名为shuffled的字符串数组的指针。我遇到的问题是,当我试图将指向数组的新指针保存到main中的另一个指针时,我开始得到奇怪的值,这些值要么引用我计算机中的文件位置,要么引用一堆数字

我将在这里发布整个代码,但您真正想了解的是返回类型、如何返回以及如何将其保存在main中。请告诉我为什么我的指针没有引用在函数中创建的工作数组。代码如下:

#include <cstdio>
#include <string>
#include <ctime>
#include <new>
#include <cstdlib>
using namespace std;

const char * getString(const char * theStrings[], unsigned int stringNum)
{
    return theStrings[stringNum];
}

string * shuffleStrings(string theStrings[])
{
    int sz = 0;
    while(!theStrings[sz].empty())
    {
        sz++;
    }
    sz--;
    int randList[sz];
    for(int p = 0; p < sz; p++)
    {
        randList[p] = sz;
    }

    srand(time(0));//seed randomizer to current time in seconds
    bool ordered = true;
    while(ordered)
    {
        int countNumberInRandList = 0;//avoid having a sz-1 member list length     (weird error I was getting)
        for(int i = 0; i < sz; i++)
        {
            int count = 0;
            int randNum = rand()%(sz+1);//get random mod-based on size
            for(int u = 0; u < sz; u++)
            {
                if(randList[u] != randNum)
                {
                    count++;
                }
            }
            if(count == sz)
            {
                randList[i] = randNum;
                countNumberInRandList++;
            }
            else
                i--;
        }
        //check to see if order is same
        int count2 = 0;
        for(int p = 0; p < sz; p++)
        {
            if(randList[p] == p)
            {
                count2++;
            }
        }
        if(count2 < sz-(sz/2) && countNumberInRandList == sz)
        {
            ordered = false;
        }
    }
    string * shuffled[sz];
    for(int r = 0; r < sz; r++) //getting random num, and str list pointer from passed in stringlist and setting that value at shuffled [ random ].
    {
        int randVal = randList[r];
        string * strListPointer = &theStrings[r];
        shuffled[randVal] = strListPointer;
    }
    for(int i = 0; i < sz; i++)
    {
        printf("element %d is %s\n", i, shuffled[i]->c_str());//correct values in a random order.
    }
    return *shuffled;
}

int main()
{
    string theSt[] = {"a", "b", "pocahontas","cashee","rawr", "okc", "mexican", "alfredo"};
    string * shuff = shuffleStrings(theSt);//if looped, you will get wrong   values
    return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
const char*getString(const char*theStrings[],unsigned int stringNum)
{
返回字符串[stringNum];
}
字符串*shuffleStrings(字符串[])
{
int sz=0;
而(!theString[sz].empty())
{
sz++;
}
sz--;
国际随机列表[sz];
对于(int p=0;pc_str());//按随机顺序更正值。
}
返回*洗牌;
}
int main()
{
字符串theSt[]={“a”、“b”、“pocahontas”、“cashee”、“rawr”、“okc”、“mexican”、“alfredo”};
string*shuff=shufflestings(theSt);//如果循环,将得到错误的值
返回0;
}

字符串分配自己的内存,不需要像字符数组那样给它们指定“长度”。您的代码有几个问题-不必详细说明,下面是一些工作/非工作示例,希望能对您有所帮助:

using std::string;

// Returns a string by value
string s1() {
  return "hello";  // This implicitly creates a std::string
}

// Also returns a string by value
string s2() {
  string s = "how are you";
  return s;
}

// Returns a pointer to a string - the caller is responsible for deleting
string* s3() {
  string* s = new string;
  *s = "this is a string";
  return s;
}

// Does not work - do not use!
string* this_does_not_work() {
  string s = "i am another string";
  // Here we are returning a pointer to a locally allocated string.
  // The string will be destroyed when this function returns, and the
  // pointer will point at some random memory, not a string! 
  // Do not do this!
  return &s;
}

int main() {
  string v1 = s1();
  // ...do things with v1...
  string v2 = s2();
  // ...do things with v2...
  string* v3 = s3();
  // ...do things with v3...
  // We now own v3 and have to deallocate it!
  delete v3;
}

这里有一大堆错误的东西——不要惊慌,这是大多数人在C和C++中围绕指针和数组第一次大脑时发生的事情。但这意味着很难找出一个错误并说“就是这样”。所以我要指出一些事情

(但提前警告:如果您询问指针被返回到
main
,您的代码确实在这方面做了一些错误,我将介绍一些错误以及如何做得更好。但这并不是您看到的错误的真正原因。)

因此,在shuffleestrings中,您正在创建一个指向字符串的指针数组(
string*shuffled[]
)。您要求
shuffleStrings
返回一个指向字符串(
string*
)的指针。你能看出这些不相配吗

在C和C++中,实际上不能绕过数组并从函数返回它们。你尝试时的行为往往会让新来者感到困惑。在某个时候,您需要理解它,但现在我只想说:您不应该实际使用
shuffleStrings
尝试返回数组

有两种更好的方法。第一个是使用一个数组,而不是一个向量,一个容器类型存在于C++中,而不是C中。如果使
shufflestings
返回
向量
(并在
shufflestings
main
中进行其他必要的更改,以使用向量而不是数组),则可以工作

vector<string *> shuffleStrings(...) {
  // ... (set things up) ...
  vector<string *> shuffled(sz);
  // ... (fill shuffled appropriately) ...
  return shuffled;
}
话虽如此,导致您出现症状的问题仍在其他地方,在
shuffleStrings
内部——毕竟,代码中的
main
从未实际使用它从
shuffleStrings
返回的指针


那么,到底出了什么问题?我还没有弄清楚你的洗牌代码到底想做什么,但我敢打赌这就是问题所在。您正在创建指向字符串的指针数组,然后填充它的一些元素——与
randList
中的数字对应的元素。但是如果
randList
中的数字没有覆盖
shuffled
中的所有有效索引,您将保留一些未初始化的指针,它们可能会指向任何地方,然后要求它们的
c_str
可能会给您带来各种各样的废话。我想这就是问题所在。

你的问题与你所说的任何东西都无关。由于您是一名初学者,我建议不要假定您的代码是正确的。相反,我建议移除那些被认为没有问题的部分,直到你除了问题什么都没有了

如果你这样做,你应该
void shuffleStrings(string * shuffled[], ...) {
  // ... (set things up) ...
  // ... (fill shuffled appropriately) ...
}

int main(...) {
  // ...
  string * shuffled[sz];
  shuffleStrings(shuffled, theSt);
  // output strings (main is probably a neater place for this
  // than shuffleStrings)
}