我有一個關於理解指針和函數如何工作的問題。 我想看看函數如何看起來像qsort()
,但我需要使用我自己的函數來交換元素和比較元素。我很驚訝地知道,我的功能不交換數據...C/C++,指針和函數的問題
我的代碼:
//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
我的數組沒有改變。
你的代碼只交換指針,而不是它們指向的東西。 – 2013-02-23 17:11:28