I am trying to extract a number of characters from a string specified by the position where it has to begin and the number of characters to be extracted. The function seems to return some garbage value and it prints some funny characters. I was debugging it but unable to figure out the reason for it.
[insert]Code:#include <stdio.h> #include <string.h> #include <stdlib.h> char* getsub(char *a, int loc, int len); int main(void) { char str[20] = "Rohan is a good boy"; char str1[20] = "Roh"; char str2[20] = "Rohan is a good boy"; char str3[20] = "Sohan"; char *sub; char s; int result; sub = getsub(str, 2, 4); printf("\n%s", sub); return 0; } char* getsub(char *a, int loc, int len) { int lenstr; int pos= 0, i,j; char str[20]; lenstr = strlen(a); for(pos = 0;pos< loc;pos++) { a++; } for(i =0; i<len;i++) { str[i]= *a; a++; } str[++i] = '\0'; return str; }



LinkBack URL
About LinkBacks



