0

I have been trying to return an array of strings for a function for a couple of days to no avail. While I was searching around StackOverflow, I found that it would be a better idea to have a parameter that will be assigned the value of an array. So, here is my code example (not the actual usage, but a mockup of how I am trying to use the function). I am sorry if the code is a bit sloppy. I have been testing things out with it for a while.

void splitOn(string message, string delim, string***toCh) {

string** rString = new string*;
string lArr[numberOf(message, delim)+1];
for(int index=0; index<numberOf(message, delim)+2; index++) {

    lArr[index]=message.substr(0, message.find(delim)).c_str();

    message = message.substr(message.find(delim)+1, message.length());
rString[index]=&lArr[index];

cout << "IN LOOP "<<*rString[index]<<endl;
}
rString[numberOf(message, string(delim))] = &message;
toCh=&rString;
}

int main(){
string***arr;
splitOn("fox.over.lazy.dog", ".", arr);
cout << **arr[0]<<endl;

Note:

  • numberOf() takes a string and a delimiter(string) and returns how many times the delimiter is found within the string.

  • strings are from std::string

  • lArr (the local array within the loop) and *rString all give correct output.

  • Although I am trying to assign the array to a parameter, learning how to return an array is more appealing to me.

I could hack this together with a file and getLine(), but I would prefer to learn how to properly do this.

4

1 に答える 1

0

決して機能しないローカル変数を返そうとしています。あなたと呼び出し元は、戻り値を割り当てる方法について合意する必要があります。コメンターが言及しているように、C++では、これは通常、ベクターへの参照を渡して割り当てを処理することによって行われます。

C では 2 つのオプションがあります。呼び出し元に十分な大きさの割り当てを渡させるか、複数の呼び出しを使用して呼び出し先で malloc することができます (呼び出し元で解放する呼び出しを忘れないでください!)。

たとえば、書き込み可能な文字配列を渡す場合、区切り文字を null 文字で上書きするだけで、新しいコピーを割り当てることなく、個々の文字列に分割できます。

于 2012-07-28T00:08:08.613 に答える