我是新的C++和我在一個函數工作洗牌串返回一個字符串*從功能型數組回主
它需要一個字符串數組,打亂他們,並返回他們回來主要。
我正在返回一個指向名爲shuffled
的字符串數組的指針。我遇到的問題是,當我嘗試將新的指針保存到數組中的另一個指針時,我開始獲取奇怪的值,這些值引用計算機中的文件位置或一堆數字。
我會在這裏發佈整個代碼,但真正想看的是返回類型,我如何返回它以及如何將它保存在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;
}
getString的寫法是錯誤的,未使用和非常嚴重不符合您的代碼的其餘部分... 作爲一個文件,儘量簡化這個問題到最小化需要重現您的問題,而不是隻問我們'找到你的錯誤'。 如果你正在嘗試學習C++;考慮使用'cout'而不是'printf'和ditcth'cstdio' ......不妨使用你正在使用的語言的功能 – UpAndAdam
在你定義你的返回類型之前,你需要明確地定義你的需求和接口。你是否試圖將用戶傳入的數組進行混洗,或者你是否試圖將它複製到一個新的數組中? – UpAndAdam
TL; DR std :: vector' –