I'm creating this function that extracts a word or part of the string from a larger string, it works perfectly but I have to use strcpy to convert it from pointer to array, is it possible to return an array?
if not possible can I work directly with pointers? I mean, using pointers instead of arrays this causes problems with header <string.h> functions ? Or I can use alla function without problem ?
#include <stdio.h>
#include <string.h>
char *substr(const char mainstring[], const int cstart, const int clength){
// printf(" %s \n ", substr("To many Strings", 8,7)); // = Strings
int main_length = 0;
int over_length = 0;
main_length = strlen(mainstring); // gets the length of mainstring[]
over_length = ( main_length - (cstart + clength)); // the value must be greater than -1 and less than the length of the mainstring[]
char *result = malloc(clength+1); // initialize by adding +1 for terminator \ 0
//That must be equal to or greater than 0 and less than the maximum length of the mainstring
if ( over_length >= 0 && over_length <= (cstart + clength)) {
strncpy(result, mainstring+cstart, clength); // copies the selected part to result
strcat(result, "\0"); // add terminator EOS end of string
}else{
printf("\n Error: Excessive size : %d", over_length); //shows when the condition is not met
}
return result;
}
int main(){
// use the function substr("String", start, length)
printf(" %s \n ", substr("To many Strings", 8,7)); // = Strings
return 0;
}