I want to extract a substring from an array of characters with a function with signature:
void substring (char str[], int start, int count, char result[]); This is my attempt:
void substring (char str[], int start, int count, char result[]) { int i; int j = 0; for(i = start; i <= count; i++) { result[j] = str[i]; j++; printf("the character in function call : %c \n", result[j]); printf("the count of j is : %i \n", j); } result[j] = '\0'; printf("the result function call : %s \n", result); } int main (void) { char pet[] = "character"; char result[40]; substring (pet, 4, 3, result); printf("the substring of character from 4, 3 step ahead is : %s \n", result); return 0; } But I get no result at all in my console window. I found another approach on the web with a while loop, but I still think that my code should be working. Why does my code not work?
for (j = 0; j < count; j++) { result[j] = str[j + start]; } result[j] = '\0';. Note that the code does not check that the string is big enough — it assumes it is OK to access the elementsstr[start]throughstr[start+count-1]without checking that there isn't an earlier null byte, etc. That may be OK — it's a design decision that should be conscious rather than unconscious, though.