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\n", stuff);
printf("%s\n", 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] = '\0';
strcat(nText, tmp);
}
return nText;
}
Your bug is here:
The buffer you return becomes invalid as soon as you return from the function.
GCC nicely warns you about this:
You have to allocate a new buffer (and the caller will have to free it), or have the caller provide output buffer (as Floris suggested).
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 thatb-a+1
is not longer than the space allocated. Thus my second method is more robust.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
In the latter case, you create space in the calling function and pass the pointer to
substring
. n your main program you would haveAs an aside, your method for copying the substring is terribly inefficient. Consider replacing it with
From this you can see that you actually need to allocate
nText[b-a+1]
elements, otherwise there is no space for the final'\0'
.