Search code examples
carraysstringpointersc89

How can I return an array of strings in an ANSI C program?


How can I return an array of strings in an ANSI C program?

For example:

#include<stdio.h>

#define SIZE 10

char ** ReturnStringArray()
{
    //How to do this?
}

main()
{
    int i=0;

    //How to do here???

    char str ** = ReturnStringArray();

    for(i=0 ; i<SIZE ; i++)
    {
        printf("%s", str[i]);
    }
}

Solution

  • You could do the following. Error checking omitted for brevity

    char** ReturnStringArray() {
      char** pArray = (char**)malloc(sizeof(char*)*SIZE);
      int i = 0;
      for ( i = 0; i < SIZE; i++ ) {
        pArray[i] = strdup("a string");
      }
      return pArray;
    }
    

    Note that you'd need to correspondingly free the returned memory.

    Additionally in your printf call you'll likely want to include a \n in your string to ensure the buffer is flushed. Otherwise the strings will get queued and won't be immediately printed to the console.

    char** str = ReturnStringArray();
    for(i=0 ; i<SIZE ; i++)
    {
        printf("%s\n", str[i]);
    }