Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return a char array from a function in C

Tags:

c

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?

#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?

like image 651
sayan Avatar asked May 08 '13 14:05

sayan


People also ask

How do you return a char function?

If you want to return a char* from a function, make sure you malloc() it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior. Voting is disabled while the site is in read-only mode.

How do I return a char pointer?

One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function. Show activity on this post. you shouldn't return data that sits on automatic storage, when you return it goes out of scope. scope and storage duration are two different beasts.

What is return type char?

char* is a pointer to the first char in the return "string" (char array). although the size of the array isn't given, in C "string"s are null terminated. meaning you can start reading the chars of the position the pointer is set to until you encounter a null char ('\0').


1 Answers

#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
like image 107
Coffee_lover Avatar answered Oct 05 '22 18:10

Coffee_lover