1 #include <stdio.h> 2 #include <stdlib.h> 3 4 5 void malloc_in_function(char **myArray, int size) 6 { 7 int i = 0; 8 9 *myArray = (char *) malloc(size * sizeof(char)); 10 if (*myArray == NULL) 11 { 12 fprintf(stderr, "Error allocating memory for myArray!\n"); 13 exit(0); 14 } 15 16 /* this is how to access array members in the function */ 17 for (i = 10; i < 20; i++) 18 { 19 /* This line will cause a segmentation fault. Why? */ 20 /* *myArray[i] = 'a' + (i - 10); */ 21 22 /* This line works much better. */ 23 (*myArray)[i] = 'a' + (i - 10); 24 } 25 } 26 27 int main(int argc, char **argv) 28 { 29 /* char myArray[20]; */ 30 char *myArray; 31 int size = 20; 32 int i = 0; 33 34 malloc_in_function(&myArray, size); 35 36 for (i = 0; i < 10; i++) 37 { 38 myArray[i] = 'A' + i; 39 } 40 41 for (i = 0; i < 20; i++) 42 { 43 printf("myArray[%d] = %c\n", i, myArray[i]); 44 } 45 46 free(myArray); 47 } 48 49 /* in main(), what does (myArray + 10) and &myArray[10] have in common? 50 * What about *(myArray + 10) and myArray[10]? 51 * What is *myArray + 10? Is it the same as myArray[0] + 10? 52 * If the malloc was for an int, would (myArray + 10) be the same as &myArray[10]? 53 */