Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c - Returning a string from function

I'm trying to make a substring function on c. It must be return "cdef", but it returns nothing. How can i fix it? Thanks.

#include<stdio.h>
#include<conio.h>
#include<string.h>

char* substring( char *, int, int );    

int main(){
    char stuff[] = "abcdefghjklmnoprstuvyz";
    printf("%s
", stuff);
    printf("%s
", substring(stuff, 2, 6));

    getch();
    return 0;
}

char* substring(char *text, int a, int b){
    char nText[b-a];
    char tmp[2];
    strcpy(nText, "");
    for(int i=a; i<b; i++){
        tmp[0] = text[i];
        tmp[1] = '';
        strcat(nText, tmp);
    }
    return nText;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are making the mistake of returning a pointer to a variable that may not exist after the function returns. You need to allocate the space in the calling function and just put the result in the space provided, or create permanent space in the function with static. Note - as pointed out by Jonathan Leffler - since the space is "permanent", you can't change the length of the block from one call to the next, and you would have to pick a "sensible" value and test that b-a+1 is not longer than the space allocated. Thus my second method is more robust.

char* substring(char *text, int a, int b){
    static char nText[100];
    if ((b-a+1)>100) // do something! you can't copy this!
    // code
    return nText;
}

As Employed Russian pointed out, using a static in this way is in any case quite dangerous since another piece of code might call this function while you're still using the result of the first call. This is NOT ADVISABLE if you do any kind of multi threading, but it's a quick fix if you have a single thread.

A better formulation is

void substring(char *text, int a, int b, char *nText) {
    // code, nothing to return
}

In the latter case, you create space in the calling function and pass the pointer to substring. n your main program you would have

char shortString[100];
substring(stuff, 4, 6, shortString);
printf("%s
", shortString);

As an aside, your method for copying the substring is terribly inefficient. Consider replacing it with

for(int i=a; i<b;i++) nText[i-a]=text[i];
nText[b-a] = '';

From this you can see that you actually need to allocate nText[b-a+1] elements, otherwise there is no space for the final ''.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...