简体   繁体   中英

Swapping 2d array (pointer to pointer) in C

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:

#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.

Too many derefencings in your swap function:

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM