View Single Post
Old Oct 14th, 2005, 8:53 PM   #3
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
This is another form of the old question about equivalence of pointers and arrays.

Although the language treats pointers and arrays as equivalent in some contexts (i.e. one can be used where the other one can) they are not exactly the same thing.

In the example;

char *strings1[5]; declares an array of five pointers. Those pointers are uninitialised, and it is necessary to make them point at something valid before they can be used.

char strings2[5][21]; is a two dimensional array of characters. strings2[i] (for i in the range [0, 4]) is a one-dimensional array of 21 characters. strings2[i], when used in an expression, is also a char * pointer.

The following expands on the example, with a few possible usages and comments about what happens;
#include <string.h>

int main()
{
     int i;

     char *strings1[5];
     char strings2[5][21];

     strcpy(strings1[3], "Hello");    /*   Undefined behaviour:  strings1[3] not initialised to point at anything */
     strcpy(strings2[3], "Hello");   /*   OK.  string2[3] is treated as a pointer   */

     for (i = 0; i < 5; ++i)
         strings1[i] = strings2[i];

     strcpy(strings1[3], "Hello");    /*   Now OK; strings1[3] equivalent to strings2[3] */
     strcpy(strings2[3], "Hello");   /*    Still OK.  Does the same as previous line   */

     for (i = 0; i < 5; ++i)
     {
         strings1[i] = (char *)0;    /* OK;  setting strings1[i] to be NULL pointer */
         strings2[i] = (char *)0;    /* Compile error.  string2[i] is not really a pointer */
     }
       
}
grumpy is offline   Reply With Quote