如何从C中的函数返回一个char数组
我想从函数返回一个字符数组。 然后我想在main
打印它。 如何在main
函数中返回字符数组?
#include #include 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; }
请告诉我,我做错了什么?
#include #include #include 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
这将编译正常,没有任何警告
-
#include stdlib.h
- pass
test=substring(i,j,s)
; - 删除
m
因为它未被使用 - 要么声明
char substring(int i,int j,char *ch)
要么在main之前定义它
Daniel是对的: http : //ideone.com/kgbo1C#view_edit_box
更改
test=substring(i,j,*s);
至
test=substring(i,j,s);
此外,您需要转发声明子字符串:
char *substring(int i,int j,char *ch); int main // ...
评论中的懒惰笔记。
#include // for malloc #include // 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