简体   繁体   中英

pointer to pointer as 2d array

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

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

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;

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
}

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