My homework is writing two function:
- Generic copy function (whose functionality is same as memcpy())
- Generic compare function (which can compare two data of any type such as int, float, double, ... ) (not using template or something which is not exist in C)
Here is my first fuction:
1 2 3 4 5 6 7 8 9 10
void* myMemcpy (void* Destination, constvoid* Source, int num)
{
char* first = (char*)Source;
char* last = (char*)Source + num;
char* result = (char*)Destination;
while (first != last)
*result++ = *first++;
return Destination;
}
But I get a problem with second function. Can you give me some advices?
Thanks for your help.
The second function should look very much like the first, except for line 7, which should compare the two values instead of copy one to the other. If the comparision is 'not equal' then your function should terminate with the appropriate 'not equal' code. Otherwise it will eventually find its way to line 9, where it should terminate with the 'equal' code (which in the case of memcmp() is zero).
By the way, you are casting away the constness of your Source, which is a Bad Thing. Don't do that. Finally, take care that your users don't give you a negative num.
1 2 3 4 5 6 7 8 9 10
void* myMemcpy (void* Destination, constvoid* Source, int num)
{
constchar* first = (constchar*)Source; // Stays const!
constchar* last = first + num; // Stays const!
char* result = (char*)Destination;
while (first < last) // No negative num allowed!
*result++ = *first++;
return Destination;
}
Hope this helps.
[edit] BTW, your professor should not be calling this "Generic Programming". It is not.
Unless I'm reading into the question a bit too far, it almost sounds as if the second one should take variable arguments and then compare the memory they occupy.
EDIT: Ah, nevermind, void* would handle the variable argument part.