Arrays of pointers that point to arrays of integers

I'm just wondering if there is a way to make an array of pointers pointing to the first column of each row in a multidimensional array of integers. As an example, consider 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:

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

I get an error message:

 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 as follows:

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

I still get the same error.

I know that we can make an array of pointers to character strings, as shown below:

 char *str[] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" } 

How to do this for arrays of integers?

+8
c arrays pointers turbo-c
source share
3 answers

Your code should work like a 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] }; 
+2
source share

If about changing the definition of daytab go as a third example, you can use this:

 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 save the save and mark the end of the array using the sentinel:

 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, in order to stay even with saving the label, the internal array also ends:

 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 ( (Type){Initialiser} ) connections used here are only available with C99.

+1
source share

Use as below

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

+1
source share

All Articles