C语言 如何从C中的函数返回一个字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16443780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to return a char array from a function in C
提问by sayan
I want to return a character array from a function. Then I want to print it in main. how can I get the character array back in mainfunction?
我想从函数返回一个字符数组。然后我想打印出来main。如何让字符数组恢复main功能?
#include<stdio.h>
#include<string.h>
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,*s);
printf("%s",test);
return 0;
}
char *substring(int i,int j,char *ch)
{
int m,n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
Please tell me what am I doing wrong?
请告诉我我做错了什么?
回答by Coffee_lover
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
int n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,s);
printf("%s",test);
free(test); //free the test
return 0;
}
This will compile fine without any warning
这将编译正常,没有任何警告
#include stdlib.h- pass
test=substring(i,j,s); - remove
mas it is unused - either declare
char substring(int i,int j,char *ch)or define it before main
#include stdlib.h- 通过
test=substring(i,j,s); - 删除,
m因为它未使用 char substring(int i,int j,char *ch)在 main 之前声明或定义它
回答by Coffee_lover
Daniel is right: http://ideone.com/kgbo1C#view_edit_box
丹尼尔是对的:http: //ideone.com/kgbo1C#view_edit_box
Change
改变
test=substring(i,j,*s);
to
到
test=substring(i,j,s);
Also, you need to forward declare substring:
此外,您需要转发声明子字符串:
char *substring(int i,int j,char *ch);
int main // ...
回答by ShinTakezou
Lazy notes in comments.
评论中的懒惰笔记。
#include <stdio.h>
// for malloc
#include <stdlib.h>
// you need the prototype
char *substring(int i,int j,char *ch);
int main(void /* std compliance */)
{
int i=0,j=2;
char s[]="String";
char *test;
// s points to the first char, S
// *s "is" the first char, S
test=substring(i,j,s); // so s only is ok
// if test == NULL, failed, give up
printf("%s",test);
free(test); // you should free it
return 0;
}
char *substring(int i,int j,char *ch)
{
int k=0;
// avoid calc same things several time
int n = j-i+1;
char *ch1;
// you can omit casting - and sizeof(char) := 1
ch1=malloc(n*sizeof(char));
// if (!ch1) error...; return NULL;
// any kind of check missing:
// are i, j ok?
// is n > 0... ch[i] is "inside" the string?...
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return ch1;
}

