fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. int main()
  5. {
  6. /* The compiler allocates space for "Hello" and '\0' (5 + 1 chars)
  7.   * and stores the address in aString1.
  8.   */
  9. const char *aString1 = "Hello";
  10. /* The compiler allocates 10 chars and initializes
  11.   * it with "World" (and the '\0' for terminator).
  12.   */
  13. const char aString2[10] = "World";
  14. /* The compiler determines length of initializer "I'm here."
  15.   * (9 + 1) and allocates the array of appropriate size.
  16.   */
  17. const char aString3[] = "I'm here.";
  18. /* allocate storage for array (3 const char*) */
  19. #if 0 /* the usual way */
  20. const char **array = malloc(3 * sizeof (const char*));
  21. #else /* how Matheus wants to do it */
  22. const char **array = NULL;
  23. array = realloc(array, 3 * sizeof (const char*));
  24. #endif /* 0 */
  25. /* assign contents (using it like an array) */
  26. array[0] = aString1;
  27. array[1] = aString2;
  28. array[2] = aString3;
  29. /* apply array to another variable array2 */
  30. const char **array2 = array; /* assigns the address only */
  31. /* use it: */
  32. printf("array2[0]: '%s', array2[1]: '%s', array2[2]: '%s'\n",
  33. array2[0], array2[1], array2[2]);
  34. /* throw away storage of array (and array2) */
  35. free(array);
  36. /* Attention! array, array2 become wild pointers at this point
  37.   * and may not be accessed (except new, valid addresses are assigned).
  38.   * However, aString1, aString2, aString3 are still intact.
  39.   */
  40. printf("aString1: '%s', aString2: '%s', aString3: '%s'\n",
  41. aString1, aString2, aString3);
  42. /* done */
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
array2[0]: 'Hello', array2[1]: 'World', array2[2]: 'I'm here.'
aString1: 'Hello', aString2: 'World', aString3: 'I'm here.'