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 ''
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…