The following is the exercise 10.4 of the book Programming in C, by Stephen Kochan. It says that I should create a function, that derives a part from an input string and returns that part back to main() (as a string, not a pointer) and displays it.
My code is below.
#include <stdio.h>
char subString (const char source[], int start, int count, char result[count + 1] ){ //result will be number of characters (count) + 1 (because of null)
int i, j, end = start + count;
// the part excluded must start from i = start and "count" number of characters must be derived and then put on result
for( i = start, j = 0; i < end; ++i, ++j)
result[j] = source[i];
result[j] = '\0';
return result[count + 1];
}
int main (void){
char result[20] = {0};
const char text1[] = "character";
result[20] = subString( text1, 4, 3, result );
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, result);
return 0;
}
And the output is
From "character" this part is being excluded-> "act"
Process returned 0 (0x0) execution time : 0.332 s
Press any key to continue.
Notice that the code above runs perfectly well - no warnings.
What i can't understand is when i replace the two lines below
result[20] = subString( text1, 4, 3, result );
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, result);
with this line
printf("From \"%s\" this part is being excluded-> \"%s\"\n", text1, subString( text1, 4, 3, result ) );
i get the output:
From "character" this part is being excluded-> "(null)"
Process returned 0 (0x0) execution time : 0.332 s
Press any key to continue.
Why is that? How can i make it work using that one line instead? Also, I'm a little confused with functions returning strings/arrays. They tend to lead me on errors, so if someone could provide me a couple of suggestions, that i should always keep in mind when working with them, that would help me very much. Thank you in advance.
result[20]. Hint:0based index.for(i = 0; i<count; i++) result[i] = source[i+start];