我有两个2d数组(指向unsigned的指针),我想交换它们。 首先,我开始编写1d指针数组的代码。这非常有效:
#include <stdio.h>
#include <stdlib.h>
void swap(unsigned **a, unsigned **b) {
unsigned * tmp = *a;
*a = *b;
*b = tmp;
}
int main() {
size_t x;
unsigned *a = (unsigned*) malloc(10*sizeof(unsigned));
unsigned *b = (unsigned*) malloc(10*sizeof(unsigned));
for(x=0;x<10;x++) a[x] = 1;
for(x=0;x<10;x++) b[x] = 0;
printf("%u %u\n",a[5],b[5]);
swap(&a, &b);
printf("%u %u\n",a[5],b[5]);
return 0;
}
我以为我可以为2D阵列做类似的事情。这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
void swap(unsigned ***a, unsigned ***b) {
unsigned ** tmp = **a;
**a = **b;
**b = tmp;
}
int main() {
size_t x,y;
unsigned **a = (unsigned**) malloc(10*sizeof(unsigned*));
unsigned **b = (unsigned**) malloc(10*sizeof(unsigned*));
for(x=0;x<10;x++)
{
a[x] = malloc(10*sizeof(unsigned));
b[x] = malloc(10*sizeof(unsigned));
}
for(x=0;x<10;x++) for(y=0;y<10;y++) a[x][y] = 1;
for(x=0;x<10;x++) for(y=0;y<10;y++) b[x][y] = 0;
printf("%u %u\n",a[5][5],b[5][5]);
swap(&a, &b);
printf("%u %u\n",a[5][5],b[5][5]);
return 0;
}
我收到两个编译器警告:
$ gcc -g -Wall test.c
test.c: In function ‘swap’:
test.c:5:21: warning: initialization from incompatible pointer type [enabled by default]
test.c:7:7: warning: assignment from incompatible pointer type [enabled by default]
我试图理解警告,但我仍然不理解它们。我不知道我的代码有什么问题。
答案 0 :(得分:3)
swap
函数中的derefencings太多:
void swap(unsigned ***a, unsigned ***b) {
unsigned ** tmp = *a;
*a = *b;
*b = tmp;
}
您想要访问指针的内容,因此您只需要取消引用一次(与原始函数相同)。
答案 1 :(得分:0)
您要做的就是交换指针,*a
指的是a[][]
的位置。
所以@didirec说,太多的derefences !!