2

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.

1
  • 2
    change to unsigned ** tmp = *a; *a = *b; *b = tmp; Commented Nov 29, 2014 at 16:21

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.