[英]Arrays of pointers that point to arrays of integers
I am just wondering if there is a way to make an array of pointers that point to the first column of each row in a multidimensional array of integers. 我只是想知道是否有一种方法可以创建一个指针数组,该指针数组指向整数整数数组中每一行的第一列。 As an example, please look at the following code:
例如,请看下面的代码:
#include <stdio.h>
int day_of_year(int year, int month, int day);
main()
{
printf("Day of year = %d\n", day_of_year(2016, 2, 1));
return 0;
}
static int daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
int day_of_year(int year, int month, int day)
{
int leap;
int *nlptr = &daytab[0][0];
int *lpptr = &daytab[1][0];
int *nlend = nlptr + month;
int *lpend = lpptr + month;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
if (leap)
for (; lpptr < lpend; lpptr++)
day += *lpptr;
else
for (; nlptr < nlend; nlptr++)
day += *nlptr;
return day;
}
When I write like this below: 当我这样写时:
int *p[2];
*p[0] = daytab[0][0];
*p[1] = daytab[1][0];
I get an error like this: 我收到这样的错误:
Error: Array must have at least one element
Error: Variable 'p' is initialized more than once
Error: { expected
Error: Variable 'p' is initialized more than once
Error: { expected
***5 errors in Compile***
I changed it like this: 我这样更改它:
int *p[2];
p[0] = &daytab[0][0];
p[1] = &daytab[1][0];
I still get the same error. 我仍然遇到相同的错误。
I know we can make an array of pointers to character strings as in the following: 我知道我们可以像下面这样创建一个指向字符串的指针数组:
char *str[] = {
"One", "Two", "Three",
"Four", "Five", "Six",
"Seven", "Eight", "Nine"
}
How do we do that for arrays of integers? 我们如何针对整数数组呢?
Your code should work as charm: 您的代码应具有魅力:
int *p[2];
p[0] = &daytab[0][0];
p[1] = &daytab[1][0];
printf("%d \n", p[0][2]); // shows: 28
printf("%d \n", p[1][2]); // shows: 29
This also works: 这也适用:
int *p[2] = { &daytab[0][0],&daytab[1][0] };
If it's about changing the definition of daytab
to go like the 3rd example you might like to use this: 如果要更改
daytab
的定义daytab
类似于第三个示例,则可能需要使用以下代码:
int * daytab[] = {
(int[]){0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
(int[]){0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
instead. 代替。
Or to stay save and mark the end of the array using a sentinel do: 或使用前哨标记保存并标记数组的结尾,请执行以下操作:
int * daytab[] = {
(int[]){0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
(int[]){0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
NULL
};
Or^2 to stay even saver marking also the inner array ends: 或^ 2甚至保留标记也将内部数组结束:
int * daytab[] = {
(int[]){0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, -1},
(int[]){0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, -1},
NULL
};
Please note that the compounds ( (Type){Initialiser}
) used here are available only from C99 on. 请注意,此处使用的化合物(
(Type){Initialiser}
)仅可从C99开始使用。
Use like below 如下使用
int *p[2];
p[0] = daytab[0];
p[1] = daytab[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.