pointer test

Apr 9, 2011 at 8:29pm
i wrote a little test to using pointers and arrays to see what the next data slot would be after the last element of a char array, and i expected it to be a string terminator ( \0 ) but instead i got some weird creepy symbol in cmd. heres the code i used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

using namespace std;

int main()
{
	char hello[5];
	char * pointer;

	pointer = hello;
	pointer += 6;

	cout << *pointer << endl << endl;
	system("pause");

	return 0;
}

run it for yourself and see what happens. can anyone help explain this?
Last edited on Apr 9, 2011 at 8:30pm
Apr 9, 2011 at 8:31pm
That's because you did not intialize your array with anything, so a) it contains garbage, and b) you are actually acessing hello[6], which is 2 chars longer than the array actually is. Remember, hello[0] is the first element.
Apr 9, 2011 at 8:47pm
same thing with this :-(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

using namespace std;

int main()
{ 
	char hello[5] = {'a', 'b', 'c', 'd', 'e'};
	char * pointer;

	pointer = hello;
	pointer += 5;

	cout << *pointer << endl << endl;
	system("pause");

	return 0;
}
Apr 9, 2011 at 8:50pm
5 is still one past the array limits, so it will be garbage. Also, when allocating an array that way, it doesn't have null terminators; only string literals do:

1
2
char test[5] = {'1', '2', '3', '4', '5'}; //no '\0' at test[4]
char argle[5] = "hi"; //has '\0' at argle[3] 
Apr 9, 2011 at 9:07pm
okay thankya :)
Topic archived. No new replies allowed.