What is so hard about allocating SizeOfControlledSequence*sizeof(data_type)?
As long as data_type is a known this will work. Strange how it looks like C++ new eh?
Code:
DWORD *m_pMap=new DWORD[size];
DWORD *m_pMap=malloc(size*sizeof(DWORD));
Code:
struct TestStruct
{
int a,b,c,d,e,f,g,h;
DWORD i,j,k,l,m,n,o,p,q;
BYTE array[400];
};
TestStruct Temp;
//Assign values to members
...
...
//Write to disk
int handle=_open("Test.dat",_O_BINARY | _O_CREAT);
if (handle!=-1)
{
_write(handle,&temp,sizeof(TestStruct));
close(handle);
}
Same idea. _write writes bytes at a time so just passing the number of data members to it won't work. It needs to know the total size of the struct to compute the total size in bytes.
When you are allocating an array, the array can be of any data type. But you can use sizeof() for the default C recognized data types like int, long, short, float, double, etc.
When you move on to C++ and use new you only need to allocate the size of the sequence. For 100 int's you simply do:
Code:
int *pArray=new int[100];
But this must allocate 100*sizeof(int) because each integer in 32-bit protected mode is 32-bits or 4 bytes. So it actually allocates 400 bytes, not 100.
A simple test proves this:
Code:
for (int i=0;i<100;i++)
{
pArray[i]=i;
printf("%d\n",pArray[i]);
}
If the memory allocation was not working this would not print 100 items. It would print 25 indexes and then crash because you can only store 25 32-bit signed/unsigned integers in 100 bytes. So it would overrun the bounds of the array. So new allocates 100 items of size (data_type), not 100 bytes. Malloc allocates bytes so you must pre-compute the size and then pass that size to malloc.
On the 26th attempt pArray[i]=i would cause an access violation if the exception was unhandled inside of Windows 2K/XP, a possible general protection fault or GPF on Windows 95/98, and a definite unrecoverable crash in DOS.
Say i have a function that is being passed two pointers to two separate arrays of doubles and that these arrays occupy the same ammount of memory. how can I:
Initialize a third pointer to the size of the other two (I don't know the number of elements in the array)
You cannot do this without knowing the size in BYTES of the array.
Knowing how many indexes or elements there are won't help on a pointer as has been said.