How to swap content of void pointers?
I'm making a function which receives array of an开发者_Go百科y datatype and reverse it elements.
void f(void *p, int size)
{
for(int i=0; i<=size/2; i++)
{
swap(p+i, p+size-i-1);
}
}
but problem is how can i implement swap function which swap their content without dereferencing void pointers?
Or you could use the std::reverse function
int main()
{
int data[] = { 1, 2, 3, 4, 5, 6, 7};
std::reverse(data, data + sizeof(data)/sizeof(data[0]));
}
Since you tagged as C++, I'm assuming that you can use template. One possible solution:
template<typename T>
void f(T *p, int size) {
for(int i=0;i<=size/2;i++) {
swap(p[i], p[size-i-1]);
}
}
An ugly C example, enjoy it:
#include <stdio.h>
void* f(void * p, size_t blockSize, size_t wholeSize){
int i;
unsigned char *begin, *end, temp;
begin = (unsigned char*) p;
end = (unsigned char*) p + wholeSize - blockSize;
while(end>begin){
for(i=0; i<blockSize; i++){
temp = begin[i];
begin[i] = end[i];
end[i] = temp;
}
begin += blockSize;
end -= blockSize;
}
return p;
}
int main()
{
int i;
double da[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int ia[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char ca[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
f(da, sizeof(da[0]), sizeof(da));
f(ia, sizeof(ia[0]), sizeof(ia));
f(ca, sizeof(ca[0]), sizeof(ca));
for(i=0; i<10; i++){
printf("da[%d]=%lf ia[%d]=%d ca[%d]=%d\n", i, da[i], i, ia[i], i, (int)ca[i]);
}
return 0;
}
If you use C++ then why not to use template
s:
template<typename T>
void f(T* const p,int size) // return changed to `void`
{
// same logic
}
This will create a copy of this function f
for any type you pass (e.g. int[]
, char[]
, A[]
). Above function can still be improved if you want:
template<typename T, int size>
void f(T (&p)[size]) // don't have to pass sizeof array explicitly
{
// same logic
}
usage:
int a[] = { ... };
f(a);
You can't do it. You need at least the size of one element of the array.
Or if it's not C but C++ you can make the function a template.
void swap(void *a, void *b, size_t size) {
char buf[size]; //can be malloc if size to too big
memcpy(temp, b, size);
memcpy(b, a, size);
memcpy(a, temp, size);
}
精彩评论