Advertisement

Saving bytes

Started by July 06, 2000 08:34 PM
-1 comments, last by Latn 24 years, 5 months ago
I was wondering if this code was correct for displaying how many bytes I saved by using pointers rather than just an array for a string:
    
#include <iostream>
using namespace std ;

int main()
{
	char *strings[] = {	"ABCDEF",
						"ABCDE" ,
						"ABCD"	} ;

	char string2[3][7] = { "ABCDEF",
						   "ABCDE" ,
						   "ABCD"	} ;


	for (int loop = 1; loop <= 3; loop++ )
	{
		cout << "line " << loop << " contains the string " << strings[loop - 1] << " at 0x" << &strings[0] << endl ;
	}

	cout << "char *strings is " << sizeof(strings) << " bytes long" << endl ;
	cout << "char string2[3][7] is " << sizeof(string2) << " bytes long" << endl ;
	cout << "using pointers saved a total of " << sizeof(string2) - sizeof(strings) << " bytes!" << endl << endl ;


	return 0 ;
}
[/source]

Also, how is it that you can get the number of elements with this: 
[source]
cout << (sizeof strings)/(sizeof strings[0]);
    
? The tutorial that I am reading saids that "The expression divides the number of bytes occupied by the whole pointer array by the number of bytes occupied by the first element of the array. Since all elements of the array occupy the same amount of memory, the result is the number of elements in the array. " I dont understand this. I know that the compiler automatically works out dimension of each index, so what if the dimension of the first index is 2 bytes and the size array is 10 bytes? Would that count as the array having 5 elements? But if the first element is 5 bytes, so now, the array shoukd have 2 elements now by the definition that was given above. I dont understand this...can someone please clear this up for me? Sorry if this post is confusing... Thanks

This topic is closed to new replies.

Advertisement