指向整数数组的指针数组

W. *_*Zhu 8 c arrays pointers turbo-c

我只是想知道是否有一种方法可以使指针数组指向多维数组整数中每行的第一列.例如,请查看以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

当我这样写时:

int *p[2];
*p[0] = daytab[0][0];
*p[1] = daytab[1][0];
Run Code Online (Sandbox Code Playgroud)

我收到这样的错误:

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***
Run Code Online (Sandbox Code Playgroud)

我这样改了:

int *p[2];
p[0] = &daytab[0][0];
p[1] = &daytab[1][0];
Run Code Online (Sandbox Code Playgroud)

我仍然得到同样的错误.

我知道我们可以创建一个指向字符串的指针数组,如下所示:

char *str[] = {
    "One", "Two", "Three",
    "Four", "Five", "Six",
    "Seven", "Eight", "Nine"
}
Run Code Online (Sandbox Code Playgroud)

我们如何为整数数组做到这一点?

Loo*_*pes 2

你的代码应该发挥魅力:

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
Run Code Online (Sandbox Code Playgroud)

这也有效:

int *p[2] = { &daytab[0][0],&daytab[1][0] };
Run Code Online (Sandbox Code Playgroud)