[英]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: 我的背景是Java,因此我不习惯使用指针,以下代码会引发错误,并且看不到方法:
#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: 您还可以将
a
初始化为双指针,例如:
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是3个整数指针的数组。 a[0],a[1] and a[2] are int pointers.
a [0],a [1]和a [2]是int指针。 You can modify a as a[0][0] = 5;
您可以将a修改为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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.