在C中交换2d数组(指针指针)

时间:2021-02-27 21:37:49

I have two 2d arrays (pointer to pointer to unsigned) and I want to swap them. First I started to write the code for 1d array of pointers. This works perfectly:

我有两个2d数组(指向无符号指针),我想交换它们。首先,我开始编写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;
}

I thought I can do something similar for 2d arrays. Here is my try:

我以为我可以为二维数组做类似的事情。这是我的尝试:

#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;
}

I got two compiler warnings:

我有两个编译器警告:

$ 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]

I tried to understand the warnings, but I still do not understand them. I have no idea what is wrong in my code.

我试图了解警告,但我仍然不理解它们。我不知道我的代码有什么问题。

2 个解决方案

#1


2  

Too many derefencings in your swap function:

交换函数中的derefencings太多:

void swap(unsigned ***a, unsigned ***b) {
  unsigned ** tmp = *a;
  *a = *b;
  *b = tmp;
}

You want to access the content of a pointer, so you only need to dereference once (same as your original function).

您想要访问指针的内容,因此您只需要取消引用一次(与原始函数相同)。

#2


0  

All you've to do is swap the pointers, and *a refers to a[][]'s location. So as @didirec said, too many derefences!!

你所要做的就是交换指针,* a指的是[] []的位置。所以@didirec说,太多的derefences !!

#1


2  

Too many derefencings in your swap function:

交换函数中的derefencings太多:

void swap(unsigned ***a, unsigned ***b) {
  unsigned ** tmp = *a;
  *a = *b;
  *b = tmp;
}

You want to access the content of a pointer, so you only need to dereference once (same as your original function).

您想要访问指针的内容,因此您只需要取消引用一次(与原始函数相同)。

#2


0  

All you've to do is swap the pointers, and *a refers to a[][]'s location. So as @didirec said, too many derefences!!

你所要做的就是交换指针,* a指的是[] []的位置。所以@didirec说,太多的derefences !!