how to return a char array from a function in C

后端 未结 3 1408
时光说笑
时光说笑 2021-02-04 05:12

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 main function?



        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 05:46

    Lazy notes in comments.

    #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

提交回复
热议问题