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