View Single Post
Old Oct 15th, 2005, 8:33 PM   #8
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,221
Rep Power: 5 grumpy is on a distinguished road
Quote:
Originally Posted by aznluvsmc
In your last example, strings[0] stores a pointer to "Hello" first. But I guess it's also a constant string (still not sure what the rules governing this are) which means strings[0] is not modifiable after that point?
Not quite. strings1[0] can be modified (in the sense that it can be reassigned to point at something else). The problem with assigning it to a string literal is that the string literal cannot be modified without invoking undefined behaviour.

So;
#include <stdlib.h>    /* so we can use malloc() */

int main()
{
    char *strings1[5];
    strings1[0] = "Hello";
    strings1[0][0] = 'A';      /* undefined behaviour as string literal is const */
    
    strings1[0] = malloc(1); /* OK: strings1[0] is a pointer, not an array */ 
    strings1[0][0] = 'A';     /* OK, if malloc() call succeeded */
    strings1[0][1] = 'B';     /*  undefined behaviour:falling off end of array */ 
}
grumpy is offline   Reply With Quote