如何在ANSI C程序中返回字符串数组?
如何在ANSI C程序中返回字符串数组 例如:如何在ANSI C程序中返回字符串数组?,c,arrays,string,pointers,c89,C,Arrays,String,Pointers,C89,如何在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++) {
#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]);
}
}
#包括
#定义尺寸10
char**ReturnStringArray()
{
//如何做到这一点?
}
main()
{
int i=0;
//在这里怎么办???
char str**=ReturnStringArray();
对于(i=0;i您可以执行以下操作。为简洁起见,省略了错误检查
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;
}
这样做
#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]);
}
}
#包括
#定义尺寸10
char**ReturnStringArray()
{
//如何做到这一点?
char**strList=(char**)malloc(sizeof(char*)*SIZE);
int i=0;
if(strList!=NULL){
对于(i=0;i 对于(i=0;i请不要键入malloc的返回,您没有包含
,正如上面有人指出的那样,缺少原型将导致int被转换为char**。不小心,您的程序可能会工作,也可能根本不工作。我也做了同样的事情。但在main()中,我写的是:-for(i=0;i@JMSA:用于(i=0;iYou未能修复代码错误,因此我的-1…请看char str**=..:p请不要在C中强制转换malloc
的返回值,否则您将无法捕获未检查malloc的原型的缺少,malloc可能返回NULL,如果SIZE>INT\u MAX,我将换行并导致索引越界uestion甚至不使用malloc
?这似乎根本不能回答问题。我的错,我提到的是tommieb post。
#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]);
}
}