我只是想知道是否有一种方法可以使指针数组指向多维整数数组中每一行的第一列。作为示例,请查看以下代码:
#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;
}
当我在下面这样写的时候:
int *p[2];
*p[0] = daytab[0][0];
*p[1] = daytab[1][0];
我收到这样的错误:
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***
我改成这样:
int *p[2];
p[0] = &daytab[0][0];
p[1] = &daytab[1][0];
我仍然遇到同样的错误。
我知道我们可以创建一个指向字符串的指针数组,如下所示:
char *str[] = {
"One", "Two", "Three",
"Four", "Five", "Six",
"Seven", "Eight", "Nine"
}
我们如何处理整数数组?
最佳答案
您的代码应该像 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
这也有效:
int *p[2] = { &daytab[0][0],&daytab[1][0] };
关于c - 指向整数数组的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236138/