How to transfer to function an array of strings? How in the same function to change the contents of the array?

  • 6
    If the question is practical, better use vector. And wherever possible, use STL. It will save a lot of time and save you from unpleasant mistakes. - skegg
  • @milillskegg: ... because arrays are evil ! - VladD
  • one
    It is easier to pass a reference to the structure within which this array is declared than the array itself. - igumnov

3 answers 3

... void foo(string* array, int length){ for(int i = 0; i < length; i++){ array[i]=array[i]+ "."; } } ... string* array = new string[20]; foo(array, 20); delete[] array; ... 
  • if the TS meant the native array, then probably the native strings. - VladD

If we are talking about sishnyh lines, here:

 ... void func(char* strings[], int c) { for(unsigned i=0;i<c;i++) cout<<strings[i]<<endl; } ... 

Somewhere in int main() :

 char* strings[5]; strings[0]="string1"; strings[1]="string2"; strings[2]="string3"; strings[3]="string4"; strings[4]="string5"; func(strings,5); 
     void foo(std::vector<std::string>& vStrings) { ... } 

    Something like this

    • one
      @Andrey Buran, @VladD, but here it is not the MASSIFE OF STRINGS that is passed to the function, but an object, a container of the template class of the STL library. Therefore, I think it’s not quite true to consider this as a solution to the problem with the transfer to the MASSIVE function of STRINGS. And so, in C ++ it is one of the most rational and convenient solutions. - Salivan
    • 3
      In C ++ char ** exists for compatibility with "C-legacy" code exclusively. It makes no sense to use this approach in the new code. It is necessary either to use containers and std :: string, or it is C with all the consequences. The task is set incorrectly, as in the joke "You either remove the cross or put on the underpants" - Andrey Buran
    • one
      @Andrey Buran, @Asen is right here, vector is not an array . By the way, among the containers there is an array . It is also not known what the author meant by speaking of strings of string or char *. - avp
    • one
      @avp something he is not an array? [] there is? there is. Is pointer arithmetic supported? Supported. Specially made for those hard-nosed ones who are trying to write in C ++ like C (actually, no). About array at this stage of development of C ++ 11, let's not. - Andrey Buran
    • one
      @Andrey Buran, array - a set of similar components (elements) located in memory directly one after another, which are accessed by index (indices). ((C) Wikipedia). And [] nothing to do with it. For any class, you can overload operator [], but it will not become an array from this. You can also write an iterator to access a variety of data types (for example, in boost :: filesystem, the directory is sequentially read through an iterator) - skegg