#include #include #include int main (int argc, char **argv) { char *name[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; char **string_ptr; int i; int arr[10][12]; int *whatever; whatever = arr[6]; /* legal */ /* arr[6] = whatever; illegal */ arr[6][5] = 47; /* legal */ arr[2][27] = 5; /* legal; equivalent to arr[4][3] = 5; */ printf ("arr[4][3] = %d\n", arr[4][3]); string_ptr = "hello"; /* legal but a bad idea! Does an implicit cast from char * to char ** */ /* printf ("string_ptr = %x; *string_ptr = %s\n", string_ptr, *string_ptr); crashes because *string_ptr is an invalid pointer */ string_ptr = (char **)calloc(10, sizeof(char *)); printf ("string_ptr = %x; *string_ptr = %s\n", string_ptr, *string_ptr); string_ptr = &name[0]; /* or equivalently string_ptr = name; */ printf ("string_ptr = %x; *string_ptr = %s\n", string_ptr, *string_ptr); name[0] = malloc(7); printf ("string_ptr = %x; *string_ptr = %s\n", string_ptr, *string_ptr); strcpy (name[0], "Sunday"); printf ("string_ptr = %x; *string_ptr = %s\n", string_ptr, *string_ptr); name[0] = name[1] = "Snarkday"; printf ("string_ptr = %x; *string_ptr = %s; string_ptr[0] = %s; string_ptr[1] = %s\n", string_ptr, *string_ptr, string_ptr[0], string_ptr[1]); name[1] = "Greenday"; printf ("string_ptr = %x; *string_ptr = %s; string_ptr[0] = %s; string_ptr[1] = %s\n", string_ptr, *string_ptr, string_ptr[0], string_ptr[1]); name[2] = "Blueday"; name[3] = "Yellowday"; /* etc. */ /* other_name[0] = "hello"; */ /* name[1][0] = 'M'; crashes because name[1] points to the literal string "Greenday" which lives in a read-only region of memory */ name[1] = strdup(name[1]); /* strdup is basically a malloc followed by a strcpy */ name[1][0] = 'M'; /* now this works */ name[1][1] = 'o'; printf ("string_ptr = %x; *string_ptr = %s; string_ptr[0] = %s; string_ptr[1] = %s\n", string_ptr, *string_ptr, string_ptr[0], string_ptr[1]); for (i = 0; i<7; ++i) printf ("name[%d] = %s\n", i, string_ptr[i]); printf ("Another day is %s\n", name[4]); /* printf ("other_name is %s\n", other_name); */ for (i=0; i