You didn't read the link.
Remember, a character string is indexed by a
pointer:
1 2 3
|
const char* foo = "Hello world!";
|
"Hello world!"
↑
foo |
A
pointer points to the memory location of the first character in the array.
Your code from lines 5 through 10, with one important adjustment:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
const char* find_surname( const char* name )
{
int index = 0;
for (int j = 0; name[j] != 0; j++) // remember, all strings end at zero
{
if (name[j] == ' ')
{
index = j + 1;
break;
}
}
return name + index; // result string is just the surname
}
|
Now you can use the function:
1 2 3
|
const char* bar = find_surname( foo );
|
"Hello world!"
↑ ↑
foo bar |
Notice that the character array is not changed. But you have a new pointer to a new "beginning" of an array -- which really isn't the true beginning, but no function will know the difference, since it only knows about the 'bar' pointer (to print, or sort, or whatever); it cannot know anything about 'foo'.
For your data, you have an array of 10 names. Each name is an array of 40 characters.
Find the surname by passing a name to the function:
1 2 3 4 5
|
for (int i = 0; i < 10; i++)
{
const char* surname = find_surname( twoD[i] );
puts( surname );
}
|
Hope this helps.