字符串数组的问题?

nochess 2003-10-29 11:52:27
我写的函数,返回值是字符串数组。因该怎么定义?

char *[] readFile(FILE *f)
{

}

编译不通过。请指教!
...全文
65 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
nochess 2003-10-30
  • 打赏
  • 举报
回复
编译错误,请看看。

Compiling...
test.cpp
e:\c\test\test.cpp(7) : error C2440: 'initializing' : cannot convert from 'void *' to 'char ** '
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
e:\c\test\test.cpp(9) : error C2440: '=' : cannot convert from 'void *' to 'char *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
e:\c\test\test.cpp(10) : error C2440: '=' : cannot convert from 'void *' to 'char *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
Error executing cl.exe.

test.obj - 3 error(s), 0 warning(s)
TianGuangZao 2003-10-30
  • 打赏
  • 举报
回复
一下子说不清,写个例子说明:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ** fun(void)
{
char **pStrArr = malloc(2 * sizeof(char *));

pStrArr[0] = malloc(4);
pStrArr[1] = malloc(4);

strcpy(pStrArr[0], "abc");
strcpy(pStrArr[1], "edg");

return pStrArr;
}


int main()
{
char **p = fun();

printf("%s\n", p[0]);
printf("%s\n", p[1]);

free(p[0]);
free(p[1]);
free(p);

return 0;
}
etheltim 2003-10-30
  • 打赏
  • 举报
回复
字符串不是一个标准类型,不能直接返回,用指针吧
sunjx119 2003-10-30
  • 打赏
  • 举报
回复
C++写了个例子用到字符串数组,希望对你有所帮助。

#include <iostream>

using namespace std;

int main()
{
char *p[5];
int i=0;

for(;i<5;++i)
{
cout<<"Input NO."<<i+1<<"country:"<<endl;
p[i]=new char[20];
cin>>p[i];
}

cout<<endl<<"The five countries you have entered:\n";
for(i=0;i<5;++i)
cout<<p[i]<<endl;

return 0;
}

TianGuangZao 2003-10-30
  • 打赏
  • 举报
回复
如果你的编译器不完全符合 ANSI C 标准。
请改成如下:
char **pStrArr = malloc(2 * sizeof(char *));
=>
char **pStrArr = (char **) malloc(2 * sizeof(char *));

pStrArr[0] = malloc(4);
=>
pStrArr[0] = (char *) malloc(4);

我看你用 C++, 一般常用 new 来动态分配内存,和 malloc 道理差不多,稍改一下就好了。
nochess 2003-10-29
  • 打赏
  • 举报
回复
这是字符数组,返回的是一个字符串。"abc"
我想返回字符串数组。{"abc"},{"edg"}}
xzygod 2003-10-29
  • 打赏
  • 举报
回复
char* readFile(FILE* f)

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧