问题描述:

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, i.e. 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.

相关阅读:
Top