1

I have a char** (a null terminate array: last element of array is NULL) returned by a function (which I can not change):

char** ptar = get_ptar();

I want to iterate over it and pass its value to another function (again which I can not change):

collection(int index, char* str);

I have this code so far:

int I = 0;
while (*ptar != 0) 
{
  collection(i, (char*)(ptar));
  ptar++; i++;
}

But it passes garbage value.

Is there a better approach get string out of a null-terminated array?


Related question:

Is there a way to get the length of char** ptar using C++11's:

std::char_traits<?>::length

Annie
  • 3,090
  • 9
  • 36
  • 74
  • 7
    `collection(i, *ptar);` – Jonathan Potter Nov 16 '14 at 18:53
  • 3
    Don't use C-style casts, use C++ casts. If you use a cast other than static_cast, something is probably (but not always) wrong. In this case, you would see that `static_cast(ptar)` does not compile, and this is your hint that something is wrong. – Neil Kirk Nov 16 '14 at 18:55
  • @Jonathan Potter, you nailed it! Thanks. – Annie Nov 16 '14 at 19:28
  • @Neil Kirk, Thanks for the tips. I am avoiding casting, it is just a middle tier where I need to pipe `char*`s to another function. – Annie Nov 16 '14 at 19:30

1 Answers1

4

Try the following:

for ( int i = 0; *( ptar + i ) != 0; i++ ) 
{
  collection( i, *( ptar + i ) );
}

Or

for ( int i = 0; ptar[i] != 0; i++ ) 
{
  collection( i, ptar[i] );
}

In C++ 2011 instead of integral constant 0 as null pointer expression you may use nullptr

To find the length of ptar you can do this:

int n = 0;

while ( ptar[n] ) ++n;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335