i need help understanding the logic behind this function, can someone please explain. the function is supposed to "Return a pointer to the character at the index given"
for example, what exactly are we declaring at "(char * const c, int index)"?
where does "index" come from or equal to in the body of the function?
1 2 3 4 5 6 7 8
char * GetValueAtIndex(char * const c, int index)
{
int i = 0;
char *p = c;
while (i++ != index)
p++;
return p;
}
"char * const c" and "int index" are the parameters for this function. They need to be passed into the function by calling code, e.g.:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
char * GetValueAtIndex(char * const c, int index)
{
int i = 0;
char *p = c;
while (i++ != index)
p++;
return p;
}
int main()
{
char* character_string = "AnExampleString";
int index = 4;
char* return_value;
return_value = GetValueAtIndex(character_string, index);
return 0;
}
The first parameter is a pointer to the character string, thats the char* bit. It is labelled as a const which stands for constant, meaning the function cannot change it. The name of the parameter is just 'c'.
The second parameter, called 'index', is just a integer value which is the position in string where you want the function to end up looking at for the return value.