returning -1 every time

i feel kind of stupid asking this, but why for the love of god is this program returning 0 every time...? its supposed to print the ascii value of a character

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;

int ascVal(size_t i, const char* p);

int main(void)
{
	char* pasc = "a";
	int (*pascVal)(size_t, const char*) = ascVal;

	cout << pascVal(strlen(pasc), pasc) << endl;

	pasc = NULL;
	return 0;
}

int ascVal(size_t i, const char* p)
{
	if (!p || i > strlen(p))
		return -1;
	else
		return p[i];
}
Last edited on
Err...

sizeof returns to size of whatever it's passed in bytes. If you pass that value as an index to an array, you'll probably end up overstepping its bounds because even with a char array (a char is 1 byte long), you'll be getting a value equal to the size of the array which is one more than the last valid index.

EDIT: Use std::strings!

-Albatross
Last edited on
It is returning 0 because the main function returns an int. It doesn't actually do anything with it after that because that signals the end of your application.
Last edited on
I think he meant his ascValu() function, not main()...

-Albatross
:o i looked at the answer and the question was messed up. they gave you the function and wanted it to be called with a pointer but in the answer the first parameter was an int not a size_t... go figure
Last edited on
Topic archived. No new replies allowed.