Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何正确交换空指针?_C++ - Fatal编程技术网

C++ 如何正确交换空指针?

C++ 如何正确交换空指针?,c++,C++,我有一个任务: 我需要通过交换函数交换数组中的元素。这是一个简单的冒泡排序算法。 但是我的void SwapInt(void*x,void*y)函数不起作用!我的意思是它正确地调用了,但什么也没做。我的预排序数组没有改变。这里可能有什么问题,如何解决 void SwapInt(void *x, void *y) { void *buffer = x; x = y; y = buffer; } bool CmpInt(void *x, void *y) { int

我有一个任务:
我需要通过交换函数交换数组中的元素。这是一个简单的冒泡排序算法。
但是我的
void SwapInt(void*x,void*y)
函数不起作用!我的意思是它正确地调用了,但什么也没做。我的预排序数组没有改变。这里可能有什么问题,如何解决

void SwapInt(void *x, void *y)
{
    void *buffer = x;
    x = y;
    y = buffer;
}

bool CmpInt(void *x, void *y)
{
    int *intPtrX = static_cast<int*>(x);
    int *intPtrY = static_cast<int*>(y);
    if(*intPtrX > *intPtrY)
        return true;
    else
        return false;
}

void Sort(int array[], int nTotal, size_t size, void (*ptrSwapInt)(void *x, void *y), bool (*ptrCmpInt)(void *x, void *y))
{
    for (int i = 0; i < nTotal; i++)
    {
        for (int j = 0; j < nTotal - 1; j++)
        {
          if (ptrCmpInt(&array[j] , &array[j + 1]))
          {
            ptrSwapInt(&array[j], &array[j + 1]);
          }
        }
    }
}
void SwapInt(void*x,void*y)
{
void*buffer=x;
x=y;
y=缓冲区;
}
bool CmpInt(无效*x,无效*y)
{
int*intPtrX=静态_转换(x);
int*intPtrY=static_cast(y);
如果(*intPtrX>*intPtrY)
返回true;
其他的
返回false;
}
void排序(int数组[],int nTotal,size\u t size,void(*ptrSwapInt)(void*x,void*y),bool(*ptrCmpInt)(void*x,void*y))
{
对于(inti=0;i

p.S我已经访问过了,但我仍然不知道出了什么问题。

你不能通过交换指针来交换整数,你必须取消对指针的引用。要做到这一点,您必须将它们转换为实际的int指针

void SwapInt(void *x, void *y)
{
    int temp = *static_cast<int*>(x);
    *static_cast<int*>(x) = *static_cast<int*>(y);
    *static_cast<int*>(y) = temp;
}
void SwapInt(void*x,void*y)
{
int temp=*静态(x);
*静态投影(x)=*静态投影(y);
*静态铸件(y)=温度;
}

事实上,您在
CmpInt
函数中做得非常正确,所以我不确定
SwapInt
中的问题是什么。

您知道有一个标准的
std::swap
函数工作得非常好,对吗?为什么你的
SwapInt
拿了两个
void*
btw?两个
int&
似乎更合适。如果要在函数外部影响这些指针,则需要一个指针或对这些指针的引用。要更改局部变量,要更改传递的内容,请使用
void SwapInt(void**x,void**y)
void SwapInt(void*&x,void*&y)
是要交换指针本身还是要交换指针指向的对象?如果
x
指向
1
并且
y
指向
2
,是否要交换
1
2
,以便
x
仍然指向同一位置,但该位置现在包含
2
?或者您想交换
x
y
以便
x
现在指向不同的位置,但该位置仍然包含它以前包含的相同
2
?这很有帮助!我想了想,但在我看来,这就像是“糟糕的风格”。现在我明白了,我是不对的。非常感谢你!整个练习的风格都不好。这是C语言中的代码,而不是C++(但我意识到这不是你的选择)。