本文介绍了交换元件结构的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的结构:

struct MyStruct {
  int iID;
  int iMyNumber;
};

然后我定义MyStructs数组:

Then I define an array of MyStructs:

struct MyStruct msTest[3];

我通过查看标识上做一个结构类似这样的排序操作。现在,只要我找出哪些记录应交换到数组排序我必须做实际的交换。我想这样的:

I'm doing a sorting operation on a struct similar to this one by looking at the ID. Now, as soon as I find out which records should be swapped to sort the array I have to do the actual swapping. I tried this:

if (iSmallest != iCntr) {
    stPTmp = &stXDB[iCntr];
    &stXDB[iCntr] = &stXDB[iSmallest];
    &stXDB[iSmallest] = &stPTmp;
}

stPTmp被定义为无效* stPTmp; iCntr iSmallest 包含记录的索引来进行交换。我的code不工作,但我怎么解决?

stPTmp is defined as void *stPTmp; and iCntr and iSmallest contain the indices of the records to be swapped. My code doesn't work, but how do I fix it?

推荐答案

您需要交换的元素,不是指针,

You need to swap elements, not pointers,

struct MyStruct stTmp;

if (iSmallest != iCntr) {
    stTmp = stXDB[iCntr];
    stXDB[iCntr] = stXDB[iSmallest];
    stXDB[iSmallest] = stTmp;
}

不是特别有效,但你的结构是小,所以它只有一点点比交换指针更贵。

Not terribly efficient, but your structs are small, so its only a bit more expensive than swapping pointers.

这篇关于交换元件结构的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:38