Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array lengths

Status
Not open for further replies.

WebDrake

Programmer
Sep 29, 2005
106
0
0
PL
Is there a maximum array length in C, other than the size of the computer's memory?

... and ... are there any functions in the standard library which might tell you the length of an array (other than [tt]strlen()[/tt], which I know about)?
 
Try
Code:
sizeof (array) / sizeof (array[0])
Note that this does not work if array is a pointer. It is a very common mistake.
 
> Is there a maximum array length in C, other than the size of the computer's memory?
It's a matter for the implementation - C itself does not limit the size of arrays.

For example, 16-bit DOS usually restricted arrays to being within one 64K segment at a time, even though the total amount of memory was much larger.

--
 
xwb said:
Try
Code:
sizeof (array) / sizeof (array[0])
Note that this does not work if array is a pointer. It is a very common mistake.
I've already fallen for that one, or rather, thought it up, found it didn't work and quickly realised why (it doesn't work for the same reason that [tt]sizeof(*a)[/tt] does work, right?).

Almost invariably when I'm dealing with arrays, they are [tt]malloc[/tt]'d pointers, so this isn't a solution. I guess there's no other way?

Thanks to you and Salem for the advice. :)
 
I wonder if you could do something like this:
Code:
char* pString = malloc( 80 + sizeof( int ) );
int* pSize = (int*)pString;
*pSize = 80;
pString += sizeof( int );
Then whenever you want to get the size, you just access the sizeof( int ) bytes before the string (or whatever type) pointer and cast it to an int.
Code:
void SomeFunc( char*  pString )
{
   int size = *(pString - sizeof( int ));
   memset( pString, '\0', size );
   ...
}
Although you'd have to remember to subtract sizeof( int ) from the pointer before you free() it.
 
If you're going to go to that amount of trouble, you may as well declare your own dynamic string
Code:
struct myStr {
  size_t  allocSize;
  size_t  usedSize;
  char    *string;
};
Along with a few access functions to create, destroy, copy, catenate (etc etc)

--
 
Assuming it's just a string he wants to use, but if he wants the length of any array types, he can do this:
Code:
void* Malloc( size_t  size )
{
   void* ptr = malloc( size + sizeof( size_t ) );
   size_t* pSize = (size_t*)ptr;
   *pSize = size;
   return (ptr + sizeof( size_t ));
}

size_t PtrLength( void*  ptr )
{
   return *(ptr - sizeof( size_t ));
}

void Free( void*  ptr )
{
   free( ptr - sizeof( size_t ) );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top