0

My background is Java therefore I'm not used to pointers, the following code throws error and I can't see way:

#include <stdio.h>
#define DIM 2
void sort_intervals(int** intervals, int n);
int main()
{
   int a[3][DIM] = {
         {1, 6} ,
         {4, 9} ,
         {3,17} };
    sort_intervals(a, 3);
  return 0;
}
void sort_intervals(int** intervals, int n)
{
  printf("%d ", intervals[0][0]);//<--- error here
}

Error: Access violation reading location

I'm not allowed to change the function signiture

Blaze
  • 16,736
  • 2
  • 25
  • 44
Devy
  • 703
  • 6
  • 17
  • 3
    Turn up your compiler warnings and don't confuse arrays with pointers :) – Quentin Mar 29 '19 at 10:37
  • 2
    `int a[3][DIM]` is not `int **`. `a` is `int (*)[DIM]`, it's a pointer to an array. – KamilCuk Mar 29 '19 at 10:37
  • @Cid I'm not allowed to change the function signiture – Devy Mar 29 '19 at 10:38
  • Then you have to change the way you are creating your array, to an `int **` – Cid Mar 29 '19 at 10:38
  • *"I'm not allowed to change the function signiture"* That is unfortunate. You actually did allocate 2D array correctly. `int**` pointer to pointer "2D" arrays tend to be more inefficient. See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/q/42094465/694733) – user694733 Mar 29 '19 at 11:13

3 Answers3

2

Then you need an array of pointers that point to arrays.

int a_1[DIM] = {1, 6};
int a_2[DIM] = { ... };
int a_3[DIM] = { ... };
int *a[3] = { a_1, a_2, a_3, }; // array of 3 pointers
sort_intervals(a, 3);

or exactly equivalent using compound literals you can:

int *a[3] = { (int[DIM]){1, 6}, (int[DIM]){2, 7}, (int[DIM]){3, 17}};
sort_intervals(a, 3);

even:

sort_intervals((int*[3]){
    (int[DIM]){1, 6},
    (int[DIM]){2, 7},
    (int[DIM]){3, 17},
}, 3);
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

I am assuming you can change main function. You could also initialize a as double pointer such as:

int **a = (int**)calloc(3, sizeof(int*)); //setting a as array of 3 pointers 
  for (int i = 0; i < 3; i++)            
     *a = (int*) calloc(DIM, sizeof(int));     //assigning pointer to a[0], a[1] and a[2]

Here a is array of 3 integer pointers. a[0],a[1] and a[2] are int pointers. You can modify a as a[0][0] = 5;

Nevus
  • 1,307
  • 1
  • 9
  • 21
1

If you can't change the signature as you explained in your comment, then you can get it done using a jagged array:

#define DIM 2
void sort_intervals(int** intervals, int n);
int main()
{
    int **a = malloc(3 * sizeof(int*));
    for (int i = 0; i < 3; i++) {
        a[i] = malloc(DIM * sizeof(int));
    }
    a[0][0] = 1; a[0][1] = 6;
    a[1][0] = 4; a[1][1] = 9;
    a[2][0] = 3; a[2][1] = 17;

    sort_intervals(a, 3);
    for (int i = 0; i < 3; i++) {
        free(a[i]);
    }
    free(a);
  return 0;
}
void sort_intervals(int** intervals, int n)
{
  printf("%d ", intervals[2][0]);//<--- error here
}
Blaze
  • 16,736
  • 2
  • 25
  • 44