Nash wrote:
Hi,
I have two different files which is filled with data from two
different structures like
struct student
{
char* name;
int age;
};
which is stored in student.dat file and another structure
struct staff
{
char *name,
int age;
int exp;
};
which is stored in staff.dat file. I have to write a function which
should read the first 20 data and write it into sepearate file. I
thought of generalizing the function so i had a function like
enum DATA
{
STUDENT,
STAFF
};
ReadWriteData(void *pData,DATA enData)
{
void * pTempStructArray;
if (enData == STUDENT)
{
pTempStructArray= new student[20];
iSizeOfStruct = sizeof(student);
}
else
{
pTempStructArray= new staff[20];
iSizeOfStruct = sizeof(staff);
}
ReadFile(hFile, &pTempStructArray [0], iSizeOfStruct,
&NumBytesReadWritten, NULL);
}
but the problem is if i try to read the data into this void pointer it
is giving some error like "error C2036: 'void *' : unknown size". Any
idea to generalize this function so that i can used the same function
to copy both the data.
The problems of this piece of code are so many that its hard to find a place to
start with. So lets just analyze what you have coded so far:
The compiler complains that it cannot evaluate the expression
"&pTempStructArray [0]"
of the statement
ReadFile(hFile, &pTempStructArray [0], ...
If examine this parameter really closely you'll find that pTempStructArray[0] is
the trouble-maker: You want to access the first element of this array. As
pTempStructArray is defined as void*, the compiler doesn't know the type of the
pointer (it knows that it is a pointer, but it doesn't know anything about the
data that is pointed to).
Thus you cannot use any pointer arithmetic on this pointer (bear in mind that
pTempStructArray[0] is in this case the same as pTempStructArray + 0). The
reason for this is that if you have a pointer "p" to some type "T", the
expression "p[number]" denotes the memory location &p plus number times the size
of T in bytes. In your case you give the compiler no information about the type
pointed to (the compiler cannot take the size of void).
You could argue that the first element of an array has the same address as the
array itself, so the compiler wouldn't need to know the size of the type pointed
to in this particular case. Although the compiler _could_ generate proper code
for this, the C++ standard certainly allows it to issue an error.
To get your code compiled you can simply pass the address of the array in the
call to ReadFile:
ReadFile(hFile, pTempStructArray, ...
will do just fine.
Having done this, you'll quickly find out about the other errors of your
programme, but this is a story for a different posting.
Regards,
Stuart