getting length of char* Array

27/08/2008 - 21:46 von Harald Klingel | Report spam
Hi guys,

I'd like to know how to get the length of an array, if I only have the
pointer to the array.

Here's an example:

class myclass{
private char* pArray;

public myclass::myclass(){
pArray = this->getArray();
cout<<"length:"<<this->getLength();
...
}

char* getArray(){
char* aTmp = new char[5];
return aTmp;
}

int getLength(){
???
return length;
}
}

As pArray is a pointer, I can't get the length of it. So I tried to get the
number of bytes of the array with sizeof(pArray), but I only get the size of
the first element (4).

How can I get the number of elements in my array?

Thank you very much,

Harald
 

Lesen sie die antworten

#1 Martin Richter [MVP]
28/08/2008 - 10:28 | Warnen spam
Hallo Harald!

Hi guys,



Deutsche Gruppe ;)

Zudem gehört natives C++ in die Gruppe microsoft.public.de.vc


char* aTmp = new char[5];
return aTmp;
}

int getLength(){
???
return length;



Es ist nicht möglich anhand eines Zeigers alleine die Größe des
allokierten Bereiches zu ermittlen. Zumindest nicht mit normalen
Bordmitteln.
Sicher es gibt _msize, aber ich würde dessen Nutzung nicht anraten.

As pArray is a pointer, I can't get the length of it. So I tried to get the
number of bytes of the array with sizeof(pArray), but I only get the size of
the first element (4).



Nein! 4 ist die Größe des Zeigers!

How can I get the number of elements in my array?



Verwende eine STL Klasse, wie vector, um so etwas zu kapseln.


Martin Richter [MVP] WWJD http://blog.m-ri.de
"A well-written program is its own heaven; a poorly written
program is its own hell!" The Tao of Programming
FAQ: http://www.mpdvc.de Samples: http://www.codeproject.com

Ähnliche fragen