簡體   English   中英

指向整數數組的指針數組

[英]Arrays of pointers that point to arrays of integers

我只是想知道是否有一種方法可以創建一個指針數組,該指針數組指向整數整數數組中每一行的第一列。 例如,請看下面的代碼:

#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"
}

我們如何針對整數數組呢?

您的代碼應具有魅力:

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] };

如果要更改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}
};

代替。

或使用前哨標記保存並標記數組的結尾,請執行以下操作:

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

或^ 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
};

請注意,此處使用的化合物( (Type){Initialiser} )僅可從C99開始使用。

如下使用

int *p[2]; p[0] = daytab[0]; p[1] = daytab[1];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM