pointer arrays

Hey i was messing around and noticed that when i do
1
2
3
4
5
6
7
8
char* a = new char[3];
	*a = 'h';
	a++;
	*a = 'i';
	a++;
	*a= '\0';
	a -= 2;
	cout << a << endl;

this prints hi
but if i do something like

1
2
3
4
5
6
7
8
int* a = new int[3];
	*a = 1;
	a++;
	*a = 2;
	a++;
	*a= 3;
	a -= 2;
	cout << a << endl;

it prints an address instead of 123. Isn't it basically the same concept though? why does the pointer to the c string print the array and the pointer to int doesnt
There is an operator>> overload for const char* that prints the C string the pointer is pointing to (or at least it would be good if it was pointing to one).
It would make no sense for other types, because we generally don't have null-terminated int arrays or null-terminated float arrays...
Last edited on
try this:
1
2
3
4
5
6
7
8
int* a = new int[3];
	*a = 1;
	a++;
	*a = 2;
	a++;
	*a= 3;
	a -= 2;
	cout << *a << endl;//you forgot *  
Yes that prints the first element, i was just wondering why with a c string the entire "array" of characters is printed if i say cout << a << endl;
but if i do that with an array of ints its not the same
AFAIK, in char * it would print the value of what pointer is point to, until null-terminated escape character is found. on int, it would print an address of the int because char * is used for characters-array, but it won't work if you write * a for accessing the pointer value for the entire array, so the way we can access the entire arrays is through the address of the first character the pointer point to.

in addition, try to write this code:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main () {
	char * arr = "string example";
	cout << arr << endl;
	arr += 3;
	cout << arr << endl;
	cin.get();
	return 0;
}


then compile and see... :D
If cout didn't treat a pointer to char that way, the only way for it to print a string literal would be to create a temporary string object, copy the literal to the string object, and then destroy the temporary string object.

That wouldn't be very good, would it?

do you mean like this:

1
2
3
4
string * temp_s = new string;
*temp_s = "temporary string";
cout << *temp_s << endl;
delete temp_s;


am i right?
Last edited on
Topic archived. No new replies allowed.