function help

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.
thank you very much for you reply, it clears things up allot. Im still a little confused with the index value.

int the while statement
1
2
3
 while (i++ !=index)
p++;
return p;


this means while "i" adds up or cycles through index, and not equal to index, p++, what is index equal to?

Sorry , i know this is probably a stupid question, im very new at this and english is my second language.

thanks
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;
}


line 16 sends a value for index to the function, right?

So you can understand this, try putting :

1
2
std::cout << return_value << std::endl;
system("Pause")

after line 16, (you'll need to #include <iostream> first), and then run it using different values for int index = 4; in line 13
Topic archived. No new replies allowed.