I think a more correct line-by-line dissection would be (slight edits to dwks' example)
Code:
1: char *
2: extract_substring ( char * str, int start, int length )
3: {
4: char * new_str = malloc( length - start + 1 );
5: strncpy( new_str, str + start, length );
6: new_str[length] = '\0';
7: return new_str;
8: }
1. The function's return value - you know that this will return a string.
2. On this line is the name of our function, which explains what it does, and the parameters required to do it. We have the original string named
str, a starting location named
start and a
length of characters to copy. All of these parameters have data types.
4. We call malloc on this line. As you should have learned from the tutorial, malloc returns at least the amount of its argument (a
size) in bytes.
5. The example uses
pointer arithmetic to start copying at the appropriate index. Without going into a lesson, it's as if we moved str by start characters and stored the value in strncpy's source argument. But this does not affect the value stored in str. We could have accomplished the same with the syntac &str[start] - what you use is up to you.
Going into a lesson, treat pointers like a ruler when you do arithmetic with pointer variables. Additiion and subtraction is like moving up and down a number line, and you can imagine the stored address moving up and down n-bytes. When you store this calculated amount (assignment) think of it like marking a spot on a ruler.
For larger data than a char, you will have to multiply by the size of the object to get the difference in addresses, but that's really low level thinking. You're almost never concerned with the size of things as much as how many elements you skipped over in the array.
The copy happens and we move on to line six.
6. This terminates the string by storing a zero at that index.
7. Then you return the string desired and the function is done.