initializing array of pointers to int 
Author Message
 initializing array of pointers to int



Tue, 25 Mar 1997 02:01:13 GMT  
 initializing array of pointers to int
Help! why doesn't this work:

#include <stdio.h>
static int *daytab[2] = {
   {0,31,28,31,30,31,30,31,31,30,31,30,55}
   {0,31,29,31,30,31,30,31,31,30,31,30,112} };  

main()
{
   int i,j;

   for (i=0; i<=1 ;i++)
      for(j=0; j<=12; j++)
         printf("ans for i=%d j=%d is %d\n",
            i,j,(int)(daytab+j)[i]);

Quote:
}

even if I use type char, it doesn't work.  seems that this only
works if I initialize and access strings, as type char.  If I use type
char and try to print as int, I get only the last int in the initialization.
is this a compiler bug?

ref K&R II 5.9

thanks in advance

I claim Dis 'er, for I have no employee 'er



Tue, 25 Mar 1997 02:17:25 GMT  
 initializing array of pointers to int

Quote:
> Help! why doesn't this work:

> #include <stdio.h>
> static int *daytab[2] = {
>    {0,31,28,31,30,31,30,31,31,30,31,30,55}
>    {0,31,29,31,30,31,30,31,31,30,31,30,112} };  

Because `int *daytab[2]' defines an array of 2 `int *' pointers, not of
2 `int[13]' arrays.  Here is code which does not use pointers:

#include <stdio.h>
static int daytab[2][13] = {
   {0,31,28,31,30,31,30,31,31,30,31,30,55},
   {0,31,29,31,30,31,30,31,31,30,31,30,112}

Quote:
};  

int main()
{
   int i, j;
   for (i = 0; i < 2; i++)
      for (j = 0; j <= 12; j++)
         printf("ans for i=%d j=%d is %d\n", i, j, daytab[i][j]);
   return 0;

Quote:
}
> seems that this only
> works if I initialize and access strings, as type char.

That's right, if you use a quoted string where a `char*' variable is
expected, the string will be allocated elsewhere and a pointer to it is
assigned to the variable.  Ie
   char *strs[2] = { "foo", "bar" };
does this:
   char foo_str[] = "foo", bar_str[] = "bar";
   char *strs[2] = { foo_str, bar_str };
and not this:
   char strs[2][4] = { "foo", "bar" };
which is the same as this:
   char strs[2][4] = { {'f', 'o', 'o', '\0'}, {'b', 'a', 'r', '\0'} };

--
Regards,

Hallvard



Tue, 25 Mar 1997 07:09:53 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. int pointer to int array

2. Initializing an int pointer

3. Initializing an array of pointers through a function

4. problems when initializing pointers to byte arrays

5. problems when initializing pointers to byte arrays

6. Initializing an array of pointers.

7. Help: initializing array of void* pointers ...

8. Initialized array of functions pointers in a class??

9. how to modify a pointer to an array one sizeof(int)

10. Sorting array of pointers to int

11. pointer to int array question

12. passing of pointers to int arrays?

 

 
Powered by phpBB® Forum Software