开发者

C: swapping pointers in an array

I have an array t开发者_如何学编程hat contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?


You need a temporary variable:

void*temp = array[4];
array[4]=array[1];
array[1] = temp;

Edit Fixed first line.


void* temp = array[1]; 
array[1] = array[4]; 
array[4] = temp;


The most correct way is using a temporary variable as in :

void *tmp_pointer;

....
tmp_pointer = array[1];
array[1] = array[4];
array[4] = tmp_pointer;
....

Stay away from any evil bit or int hacks! :)

Let me add here that we should have asked "what type of pointer?"

In theory, you can't safely mix pointers to data and pointers to function. The C standard does not guarantee that this would be meaningful or possible at all. It only ensures that:

  • data pointers can be converted back and from void *
  • ((void *)0) is a pointer that is different from any data pointer or function pointer
  • function pointers of one type can be converted to function pointers of another type and back.

I understand that this is because in some architecture, the address space for data is completely separated from the address space for functions and you can't safely convert from on type of pointers to the other and back.


#include <stdint.h>
if (1 != 4) {
    array[1] = (void*)((intptr_t)(array[1]) ^ (intptr_t)(array[4]));
    array[4] = (void*)((intptr_t)(array[1]) ^ (intptr_t)(array[4]));
    array[1] = (void*)((intptr_t)(array[1]) ^ (intptr_t)(array[4]));
}

Is much clearer and saves a temporary. ;-)


My C is quite rusty, but a simple

int* foo = array[4];
array[4] = array[1];
array[1] = foo;

should suffice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜