26
Aug
0

C++ – knowing array size dynamically

I see many time the fallowing questions : How to know the size of an array? How To Get Array Length?
And because I needed it a few months ago, here is the answer!

Edit : It seems that this code does not work on linux/unix (in others words, it works only on windows!), then have a look to malloc_usable_size if your are working on linux.

Code

// We use Qt just for the style
#include <QtCore/QCoreApplication>

/** Qt based consol application */
void Print(const QString& sentence, int param){
	qWarning(sentence.arg(param).toLatin1());
}

/**
* This program shows the more simple and useful way to
* know the size of an array in C++
*/

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

	{ // Static allocating
		int tab[10];

		// We cannot use _msize without allocating memory
		// without new or malloc
		int sizeSO = sizeof(tab)/sizeof(*tab);

		Print("Size of tab with sizeof = %1",sizeSO);
	}

	{ // Malloc
		int * tabmalloc = static_cast<int*>(malloc(sizeof(int) * 10));

		int sizeMS = _msize(tabmalloc)/sizeof(*tabmalloc);
		int sizeSO = sizeof(tabmalloc)/sizeof(*tabmalloc);

		Print("Size of tabmalloc with msize = %1",sizeMS);
		Print("Size of tabmalloc with sizeof = %1",sizeSO);

		free(tabmalloc);
	}

	{ // New
		int * tabnew = new int[10];

		int sizeMS = _msize(tabnew)/sizeof(*tabnew);
		int sizeSO = sizeof(tabnew)/sizeof(*tabnew);

		Print("Size of tabnew with msize = %1",sizeMS);
		Print("Size of tabnew with sizeof = %1",sizeSO);

		delete [] tabnew;
	}

    return a.exec();
}

Results

Size of tab with sizeof = 10
Size of tabmalloc with msize = 10
Size of tabmalloc with sizeof = 1
Size of tabnew with msize = 10
Size of tabnew with sizeof = 1
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.

Comments are closed.

Celadon theme by the Themes Boutique