How to handle char pointer ?

Hello,
I'm using the snippet below to understand how to handle char pointers.
This snippet shows the string char by char.

I understand "m" is a pointer, right ? But I was not able to handle it directly (like using m++) and so I used "n".

Can I handle "m" direclty ?

1
2
3
4
5
6
7
8
9
10
char m[80];
strcpy (m,"hello");

char* n;
n=m;
while (*n)
{
 std::cout << *n << std::endl;
 n++;
}


Thank you
Marcio
Yes, in this case you can. Later on, you'll see that sometimes you can't lose a pointer or you'll produce a memory leak. But don't concern yourself with it yet.
Ok, but if I make the code as below, I get the following error:

error: ISO C++ forbids cast to non-reference type used as lvalue
error: non-lvalue in assignment
Build error occurred, build is stopped

1
2
3
4
5
6
7
8
char m[80];
strcpy (m,"hello");

while (*m)
{
 std::cout << *m << std::endl;
 m++;
}
Huh. I guess I was wrong.
A pointer holds the address of a variable. In the case of char* n, by assigning it the value of m, you are actually making this assignment:

n = &m[0]

That's because C/C++ provides two ways to refer to the first element of an array, T; &T[0] and T. A pointer variable contains an address but an address isn't a pointer. That is, m is the address of the array but isn't a pointer to itself.

Consider this; m++; is equivalent to the statement m = m+1; Now, since m is another way of writing &m[0], then this is the same as making the following assignment:

&m[0] = &m[0] + 1;

If this was allowed, the address of the first element of an array would now be the same as the address of the second element of the same array. Hopefully, you see that this would make no sense. Indeed, the left side of this statement is not allowed to be on the left side of an assignmnt, which is what the second error message is telling you "error: non-lvalue in assignment"

Your use of char* n is correct and is what you should use to reference the elements of the array m.

So, in "char m[80]", despite m has an address, it is NOT a pointer ( m is an array !!)

But in "char * n", n is a pointer (and so it should hold an address).

And with "n=m", now I have a pointer to handle.

Cristal Clear ... Thank you.
Last edited on
You've got it.

For a more complete understanding of pointers, I suggest reading http://www.cplusplus.com/doc/tutorial/pointers.html.


Good luck.
Topic archived. No new replies allowed.