[英]how to return a char array from a function in C
I want to return a character array from a function. 我想从函数返回一个字符数组。 Then I want to print it in
main
. 然后我想在
main
打印它。 how can I get the character array back in main
function? 如何在
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? 请告诉我,我做错了什么?
#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
test=substring(i,j,s)
; test=substring(i,j,s)
; m
as it is unused m
因为它未被使用 char substring(int i,int j,char *ch)
or define it before main char substring(int i,int j,char *ch)
要么在main之前定义它 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 // ...
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.