how to return a char array from a function in C

后端 未结 3 1409
时光说笑
时光说笑 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
    #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

    1. #include stdlib.h
    2. pass test=substring(i,j,s);
    3. remove m as it is unused
    4. either declare char substring(int i,int j,char *ch) or define it before main
    0 讨论(0)
  • 2021-02-04 05:46

    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;
    }
    
    0 讨论(0)
  • 2021-02-04 05:54

    Daniel is right: 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 // ...
    
    0 讨论(0)
提交回复
热议问题