c - 指向整数数组的指针数组

标签 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;
}

当我在下面这样写的时候:

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/

相关文章:

c - 如何在 gcc make 中链接静态库?

c - ELF - 更改入口点时出现 SEGFAULT

c - 编写一个 C 程序,将数组中的数字排列为一系列奇数和偶数

java - 自定义异常(exception)或空列表

c++ - 段错误 - 将变量传递给方法会更改全局值

c - 循环内的 fscanf

c - 添加到链表的头部

arrays - 我想将循环的结果存储到数组中

c - 是否可以将指针从结构类型转换为扩展 C 中第一个结构类型的另一种结构类型?

c - 不同的指针是否被认为是不同的数据类型?