0

So many of you maybe think that it is an answered question, but my situation is qiuet different //becouse i declare array IN the FUNCTION//. The matter is: i want to make a string splitter, which separates a string into chunks which will be part of an array. The basic source code is:

string separate(string str, int chunk, string mode = "res2end"){

int strlen = str.length();

int full = strlen / chunk;

int arr_size = full+1;

string result[arr_size]; //this is the 25th row

int modf = strlen % chunk;

    for(unsigned i=0; i<full; i++){
        int msr = i*chunk;
        int sp = msr - chunk;
        string subres = str.substr(msr, chunk);
        result[i] = subres;
    }

    if(modf != 0){
        int restm = strlen - (full * chunk);
        result[full+1] = str.substr(restm, modf);
    }

return result;
}

As you see, i tried to set the lenght of the array but nothing! There is an error message:

..\fc.h(25) : error C2057: expected constant expression
..\fc.h(25) : error C2466: cannot allocate an array of constant size 0
..\fc.h(25) : error C2133: 'result' : unknown size

So if anyone should share with me the solution i would be very pleased!

1
  • string result[arr_size]; is not legal C++. Your compiler might support it, but arr_size needs to be a compile time constant. Use std::vector<std::string> as type for result and as return type. Commented Jan 31, 2015 at 21:34

3 Answers 3

2

Variable-Length Arrays (VLAs) are not part of the C++ standard (yet ?).

You should use a dynamically-allocated array, for which your best bet is std::vector. This will also enable you to return the array at all, since you can't return raw arrays from (or pass arrays to) functions either. Mind changing the return type, too.

Sign up to request clarification or add additional context in comments.

Comments

0
std::vector< string > separate(string str, size_t chunk, string mode = "res2end"){
    size_t strlen = str.length();
    size_t full = strlen / chunk;
    std::vector< string > result; //this is the 25th row
    int modf = strlen % chunk;

    for(size_t i=0; i<full; i++){
        int msr = i*chunk;
        int sp = msr - chunk;
        result.push_back( str.substr(msr, chunk));
    }

    if(modf){
        int restm = strlen - (full * chunk);
        result.push_back( str.substr(restm, modf) );
    }

    return result;  // This could be a costly copy if prior to move introduced in C++11
}

Comments

0

You are creating an array of strings, not a single string. Your function returns single string, but "result" variable is an array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.