Returning an Array of Strings
in a Parameter


Passing the Address of an Array of Strings: In the middle example below, we pass the address of an array of strings, give the array of strings a value, return it through the parameter (since this parameter is a pointer to an array of strings) and print it in the calling program. This middle method is the one you are supposed to imitate in Recitation 8. On the left is an incorrect method. On the right is a another correct method, which passes just a array of strings, but with its main array of pointers already allocated. Notice that the variable q on the right is not at all the same as the variable q on the left and in the middle.

These examples do not free their allocated storage, as they ought to.

Questions (in the recitation):

  1. What is wrong with the program on the left?
  2. Why does the call to mess_up seem to cause the problem to occur?

Incorrect Method Correct Method (Use for Rec 8) Another Correct Method
#include <stdio.h>

void create_string(char ***q) {
   char *name [] =
      

      {"Neal",
       "R.",
       "Wagner",
        NULL};
   *q = name;
}

void mess_up() { /* stack */
   int a[20];
   int i;
   for (i = 0; i < 20; i++)
      a[i]= i;
}

void print_string(char **p) {
   while (*p)
      printf("%s ", *(p++));
   printf("\n");
}

int main() {
   char **p;
   
   
   create_string(&p);
   print_string(p);
   mess_up();
   print_string(p);
}
#include <stdio.h>

void create_string(char ***q) {
   char **name =
      (char **)
       malloc(sizeof(char *)*4);
   *name     = "Neal";
   *(name+1) = "R.";
   *(name+2) = "Wagner"; 
   *(name+3) = NULL;
   *q = name;
}

void mess_up() {
   int a[20];
   int i;
   for (i = 0; i < 20; i++)
      a[i]= i;
}

void print_string(char **p) {
   while (*p)
      printf("%s ", *(p++));
   printf("\n");
}

int main() {
   char **p;
   
   
   create_string(&p);
   print_string(p);
   mess_up();
   print_string(p);
}
#include <stdio.h>

void create_string(char **q) {
   
   
   
   *q     = "Neal";
   *(q+1) = "R.";
   *(q+2) = "Wagner"; 
   *(q+3) = NULL;
}


void mess_up() {
   int a[20];
   int i;
   for (i = 0; i < 20; i++)
      a[i]= i;
}

void print_string(char **p) {
   while (*p)
      printf("%s ", *(p++));
   printf("\n");
}

int main() {
   char **p =
      (char **)
       malloc(sizeof(char *)*4);
   create_string(p);
   print_string(p);
   mess_up();
   print_string(p);
}
% cc -o param_wrong param_wrong.c
% param_wrong
Neal R. Wagner
Segmentation fault
% cc -o param param.c
% param
Neal R. Wagner
Neal R. Wagner
% cc -o param2 param2.c
% param2
Neal R. Wagner
Neal R. Wagner