我有一个关于了解指针和函数如何工作的小问题。我想看看一个函数的样子qsort()
,但我需要使用我自己的函数来交换元素和比较元素。我很惊讶地知道我的函数不交换数据......
我的代码:
//prototypes file: other.h
void Sort(char* pcFirst, int nNumber, int size, void (*Swap)(void*, void*), int (*Compare)(void*, void*) ); //sorts any arrays
void SwapInt(void* p1, void* p2); // swap pointers
int CmpInt(void* p1, void* p2); // compare poineters
//realisation file: other.cpp
#include "other.h"
void Sort(char* pcFirst, int nNumber, int size,
void (*Swap)(void*, void*), int (*Compare)(void*, void*) )
{
int i;
for( i = 1; i < nNumber; i++)
for(int j = nNumber - 1; j >= i; j--)
{
char* pCurrent = pcFirst + j * size;
char* pPrevious = pcFirst + (j - 1) * size;
if( (*Compare)( pPrevious, pCurrent ) > 0 )// if > 0 then Swap
{
(*Swap)( pPrevious, pCurrent );
}
}
}
void SwapInt(void* p1, void* p2)
{
int * ptmp1 = static_cast<int*>(p1);
int * ptmp2 = static_cast<int*>(p2);
int * ptmp = ptmp1;
ptmp1 = ptmp2;
ptmp2 = ptmp;
}
int CmpInt(void* p1, void* p2)
{
int nResult;
int * ptmp1 = static_cast<int*>(p1);
int * ptmp2 = static_cast<int*>(p2);
nResult = (*ptmp1 - *ptmp2);
return nResult;
}
//main file: lab.cpp
#include <tchar.h>
#include <iostream>
#include <cstdio>
#include <cmath>
#include "other.h"
int _tmain()
{
int nAr[] = {33,44,55,22,11}; //array for sort
int nTotal = sizeof(nAr) / sizeof(int); //number of elements
for ( int i = 0; i < nTotal; i++)
{
printf("%d ",nAr[i]); // result of cycle is 33 44 55 22 11
}
Sort(reinterpret_cast<char*>(&nAr[0]), nTotal, sizeof(int), SwapInt, CmpInt);
for ( int i = 0; i < nTotal; i++)
{
printf("%d ",nAr[i]); // result of cycle is 33 44 55 22 11 too =(
}
}
为什么数组没有变化?
在调试器中,我可以看到所有指针都发生了变化,并获得了正确的值,但在main
我的数组中没有改变。