简体   繁体   中英

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]);
    }
}

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]);
}

Do it this way

#include<stdio.h>

#define SIZE 10

char ** ReturnStringArray()
{
    //How to do this?
    char **strList = (char **)malloc(sizeof(char*) * SIZE);
    int i = 0;
    if (strList != NULL){
         for (i = 0; i < SIZE; i++){
             strList[i] = (char *)malloc(SIZE * sizeof(char) + 1);
             if (strList[i] != NULL){
                sprintf(strList[i], "Foo%d", i);
             }
         }
    }
    return strList;
}

main()
{
    int i=0;

    //How to do here???

    char **str = ReturnStringArray();

    for(i=0 ; i<SIZE ; i++)
    {
        printf("%s", str[i]);
    }
}
  • Problem 1: Your double pointer declaration was incorrect
  • Problem 2: You need to know the size of the string for each pointer in the double-pointer..
  • Problem 3: The onus is placed on you to free the memory when done with it..

The code sample above assumes that the maximum size of the string will not exceed the value of SIZE , ie 10 bytes in length...

Do not go beyond the boundary of the double pointer as it will crash

pls dont typecast the return of malloc, you have not included <stdlib.h> and as someone pointed out above lack of prototype will result in int being casted to char **. Accidently your program may or may not work at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM