如何在 ANSI C 程序中返回字符串数组?
如何在 ANSI C 程序中返回字符串数组?
例如:
#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]);
}
}
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]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行以下操作。为简洁起见,省略了错误检查
请注意,您需要相应地释放返回的内存。
此外,在 printf 调用中,您可能需要在字符串中包含
\n
以确保刷新缓冲区。否则,字符串将排队并且不会立即打印到控制台。You could do the following. Error checking omitted for brevity
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.这样做
的代码示例假设字符串的最大大小不会超过
SIZE
的值,即长度为 10 个字节...不要超出双指针的边界,如它会崩溃
Do it this way
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
请不要对 malloc 的返回进行类型转换,您还没有包含
并且正如上面有人指出的,缺少原型将导致 int 被转换为 char **。意外地,您的程序可能会也可能根本无法运行。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.