简体   繁体   English

如何在ANSI C程序中返回字符串数组?

[英]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? 如何在ANSI C程序中返回字符串数组?

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. 另外,在您的printf调用中,您可能希望在字符串中包含\\n以确保刷新了缓冲区。 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 问题1:您的双指针声明不正确
  • Problem 2: You need to know the size of the string for each pointer in the double-pointer.. 问题2:您需要知道双指针中每个指针的字符串大小。
  • Problem 3: The onus is placed on you to free the memory when done with it.. 问题3:完成后,您有责任负担释放内存的责任。

The code sample above assumes that the maximum size of the string will not exceed the value of SIZE , ie 10 bytes in length... 上面的代码示例假定字符串的最大大小不会超过SIZE的值,即长度为10个字节...

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 **. 请不要强制转换malloc的返回值,您还没有包含<stdlib.h> ,正如有人指出,缺少原型会导致将int强制转换为char **。 Accidently your program may or may not work at all. 偶然地,您的程序可能会也可能根本无法工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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