simple C++ link file test

Hello,

i am trying to figure out why it doesnt print 1 letter at a time like this in console:
T
E
S
T
but instead prints:
Test
est
st
t

can anyone explain why? also playing with pointers a little bit :P

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

void message(const char* message);

int main()
{
	int x = 0;
	char* test = "test";

	while (x <= 3)
	{
		message(&test[x]);
		x++;
	}

	std::cin.get();
}

1
2
3
4
5
6
#include <iostream>

void message(const char* message)
{
	std::cout << message << std::endl;
}
Hello siten0308,

Line 12 is sending the address of the array with an offset of "x". First time through the loop this is the beginning of the array. The second time through "x" is equal to 1, so it is send the address of the array "test" with an offset of 1 char. And so on.

Then in the "message" function the first time it is being sent the start of the array, so it prints from start until it finds a "\0". The second time address sent is the start of the array + 1, so it starts there and prints until it finds a "\0".

Now if you want to only print one character you will need to change the "message function and tell it to print only 1 character. As in std::cout << message[0] << std::endl;

I also had to change line 8 because it was wrong. char test[]{ "test" };

Now "test" is defined as a character array that can hold a string. As you have it you are trying to put a string in a variable that can only hold a pointer, i.e., an address.

FYI in the function "message" the array, or in this case the address, sent to the function degrades to a pointer. That is why your function definition works.

Hope that helps,

Andy
Gotya thank you Handy Andy :)

makes sense now, so if i want to print out lets say:
T
E
S
T

plus the memory of each letter,
would i do something like:

char* mem;

then in the while loop, how would i do that?

thanks again for your help :)
Topic archived. No new replies allowed.