Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as a parameter

I have created an array:

CString* pstrArray = new CString[nMySize];

Now how can I pass it to a function to be filled up? What is the actual parameter?

void FillThisArray(what goes here?)
{
}
like image 912
Sunscreen Avatar asked Nov 26 '10 08:11

Sunscreen


2 Answers

You should use a container class: CStringArray

void FillThisArray( CStringArray & rMyStrings )

If you don't want this (I don't see any possible reason, but anyway):

void FillThisArray(CString* strings, size_t num)
{
  // example
  for( size_t s=0; s<num; s++ )
  {
    strings[s].Format( _T("This is the %d. string"), s+1 );
  }
}
like image 110
ur. Avatar answered Sep 21 '22 13:09

ur.


CString* pstrArray = NULL; pstrArray = new CString[nMySize];

For simplicity:

CString* pstrArray = new CString[nMySize];

Now how can i pass it to a function to be filled up? What is the actual parameter?
void FillThisArray(????) { }

The most obvious interface is:

void FillThisArray(CString* pstrArray, size_t n)

Taking a step back:

  • be aware that all the memory for nMySize default-constructed CStrings will be allocated by that single new statement
  • you should consider using a std::vector<std::string>
    • std::vector because:
      • automatically deletes the memory for all the strings when it goes out of scope
      • by default the memory usage will increase more gradually as strings are added using e.g. push_back(), and in such usage can grow beyond the initial size without any special work on your part
      • you can proactively reserve space for nMySize strings, and/or create them, when you construct the vector if you really want that behaviour
    • std::string because:
      • it's the portable string type defined by the C++ Standard, and reduces lock in to your dependencies
      • that said, it may be impractical or inefficient to avoid in some circumstances
like image 29
Tony Delroy Avatar answered Sep 20 '22 13:09

Tony Delroy