Learning pointers in C++

J

Javier

Hi

I'm trying to learn how to use pointers with a little example.

I did:

void main(int argc, char* argv[])
{
char algo[] = "Algo mas";
char * p = algo;
char otra[256] = " ";
otra = *p;

printf("%s", otra);
}

I tried to assign a value to algo, then tried to assign algo to a
pointer p and then tried to assign the value pointed by p to otra.

Program compiles ok but when I try to run it, hangs up :(

What I'm doing wrong ?

Thanks in advance

J
 
K

Karl Heinz Buchegger

Javier said:
Hi

I'm trying to learn how to use pointers with a little example.

I did:

void main(int argc, char* argv[])
{
char algo[] = "Algo mas";
char * p = algo;
char otra[256] = " ";
otra = *p;

printf("%s", otra);
}

I tried to assign a value to algo, then tried to assign algo to a
pointer p and then tried to assign the value pointed by p to otra.

Program compiles ok

Which compiler?
I am just asking, because if your compiler indeed compiled the above
program without an error, it has a serious bug.
*** You can't assign to an array ***
otra is an array, thus the assignment
otra = *p;
is illegal!
but when I try to run it, hangs up :(

What did you do:
First the pgm creates an array and initializes it with the characters
'A' 'l' 'g' 'o' ' ' 'm' 'a' 's' '\0'

char algo[] = "Algo mas";

algo
+---+---+---+---+---+---+---+---+---+
| A | l | g | o | | m | a | s | \0|
+---+---+---+---+---+---+---+---+---+

Then a pointer is created, which points to the beginning of algo.
This works, because in that context the name of the array alon ('algo')
depractes to the address of the first array element.

char * p = algo;

algo
+---+---+---+---+---+---+---+---+---+
| A | l | g | o | | m | a | s | \0|
+---+---+---+---+---+---+---+---+---+
^
|
+------------+
|
p |
+-------+ |
| o----------+
+-------+

Next another array is created, this time it has a length of 256 characters
and is initialized with the characters ' ' '\0'. Note: since this are only
2 characters, this also means that the remaining 254 characters are not
touched. They contain garbage.

char otra[256] = " ";

algo
+---+---+---+---+---+---+---+---+---+
| A | l | g | o | | m | a | s | \0|
+---+---+---+---+---+---+---+---+---+
^
|
+------------+
|
p |
+-------+ |
| o----------+
+-------+


otra
+---+---+---+-- ... ---+---+---+
| | \0| xx| x xx| xx| xx|
+---+---+---+-- ... ---+---+---+

Then comes the illegal statement:

otra = *p;

I don't know what your compiler did with that, lets just say
you wrote:

otra[0] = *p;

Then the following would happen:
left side of assignment: Thats easy, just look up 'otra' and identify
the element with index 0. This element will get a new value.
right side of assignment: Look up 'p'. There is an array emitting from
it. The '*' in *p tells the program to follow that arrow und use whatever
is at the end of that arrow. So the Arrow is pointing to the character A.
Thus otra[0] will get this as new value:

algo
+---+---+---+---+---+---+---+---+---+
| A | l | g | o | | m | a | s | \0|
+---+---+---+---+---+---+---+---+---+
^
|
+------------+
|
p |
+-------+ |
| o----------+
+-------+


otra
+---+---+---+-- ... ---+---+---+
| A | \0| xx| x xx| xx| xx|
+---+---+---+-- ... ---+---+---+

printf( "%s", otra );

This outputs "A", since otra contains a valid C style string, which
consists of the characters 'A' and '\0'. printf starts its output at
otra[0] and stops it at otra[1], since there is a '\0' character.

But: double check the posted program with the one you compiled. The
version you posted is illegal and no compiler should compile it without
an error message.
 
S

Shezan Baig

Javier said:
Hi

I'm trying to learn how to use pointers with a little example.

I did:

void main(int argc, char* argv[])
{
char algo[] = "Algo mas";
char * p = algo;
char otra[256] = " ";
otra = *p;

I believe you want:
*otra = *p;

or simply:
otra[0] = *p;

Hope this helps,
-shez-
 
J

Javier

Karl said:
Javier said:
Hi

I'm trying to learn how to use pointers with a little example.

I did:

void main(int argc, char* argv[])
{
char algo[] = "Algo mas";
char * p = algo;
char otra[256] = " ";
otra = *p;

printf("%s", otra);
}

I tried to assign a value to algo, then tried to assign algo to a
pointer p and then tried to assign the value pointed by p to otra.

Program compiles ok


Which compiler?
I am just asking, because if your compiler indeed compiled the above
program without an error, it has a serious bug.
*** You can't assign to an array ***
otra is an array, thus the assignment
otra = *p;
is illegal!


.............

Hi

Thanks a lot for your clear reply.

I understand you but I'm confused about some thing: how could I assign a
string to a variable, then assign this variable address to a char
pointer and then assign the pointed for the char pointer to a new string
variable ?

Should I use strcpy or could I just assign values ?

Sorry for that kind of questions but I used to program with C more than
10 years ago and now, after more than 10 years programming with PHP and
Java (without pointers), I'm feeling myself like newbie...so frustrant
for me...

Thanks in advance

J
 
S

Shezan Baig

Javier said:
I understand you but I'm confused about some thing: how could I assign a
string to a variable, then assign this variable address to a char
pointer and then assign the pointed for the char pointer to a new string
variable ?

Should I use strcpy or could I just assign values ?

Sorry for that kind of questions but I used to program with C more than
10 years ago and now, after more than 10 years programming with PHP and
Java (without pointers), I'm feeling myself like newbie...so frustrant
for me...

This is exactly the reason to use the standard C++ containers (less
hassle with pointers etc). Remember, C++ is not C. Have a look at the
"std::string" class, I'm sure it will be much easier to use.

Hope this helps,
-shez-
 
T

Tim Love

Javier said:
I'm trying to learn how to use pointers with a little example.
...
Should I use strcpy or could I just assign values ?
...
Sorry for that kind of questions but I used to program with C more than
10 years ago and now, after more than 10 years programming with PHP and
Java (without pointers),
Perhaps your history with C is affecting your view of modern C++.
I think nowadays pointers are less necessary in C++ than they used to be
in C. References, <string>, etc are used. E.g
-----
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
s="hello";
s=s+" world";
cout << s << endl;
}
-----
is safer and more readable than the buggy
-----
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[10];
strcpy(s,"hello");
strcat(s," world");
cout << s << endl;
}
 
N

Noah Roberts

Karl said:
otra
+---+---+---+-- ... ---+---+---+
| A | \0| xx| x xx| xx| xx|
+---+---+---+-- ... ---+---+---+

Where did the NUL in otra[1] come from? I didn't see you assign it...

Unless you did, it isn't there. The printf following would then
possibly segfault. That is usually what happens, but I believe the
results are undefined.

When using C style char* you have to be VERY careful, and VERY specific
about every damn thing you do. That is why std::string is so much more
happy.

To the OP:

I would recommend that if you are going to learn C++ you learn how to
use the C++ library. Messing with char* is not common when you are
using the C++ stdlib to its full capabilities (in fact actual pointers
are a dieing breed also). Get a book that teaches using the stdlib and
not the old 'C++ as a different kind of C' type fire starters.

Eventually you will want to learn arrays, pointers, and all that char*
crap (because it pays to understand it), but for now just focus on
learning the stdlib, which includes such things as vectors and strings.

For instance:

std::string str = "Albino aligator"; // or whatever...
std::string *pstr = &str; // Why? I don't know...
std::string copy = *pstr;

See how much easier that is?! Now lets do it the hard way...

What you need to do in your *C* code is:

char str[] = "Albino aligator";
char *pstr = str;
char *copy;

copy = (char*)malloc(strlen(pstr) + 1);
if (copy == NULL) abort_program();

strncpy(copy, pstr, strlen(pstr));

I also didn't make sure that I /could/ copy my strings in the C++
version (if copy == NULL in C). I don't have to unless I want to avoid
aborting the program. If I do I have to try the copy and catch any
possible exceptions.
 
C

Clark S. Cox III

Hi

I'm trying to learn how to use pointers with a little example.

I did:

void main(int argc, char* argv[])
{
char algo[] = "Algo mas";
char * p = algo;
char otra[256] = " ";
otra = *p;

printf("%s", otra);
}

I tried to assign a value to algo, then tried to assign algo to a
pointer p and then tried to assign the value pointed by p to otra.

Program compiles ok but when I try to run it, hangs up :(

I highly doubt that it compiles ok. If it does, then your compiler is broken.

This line in particular:
otra = *p;

You're trying to assign something to an array, which isn't legal.
What I'm doing wrong ?

That depends on what you're trying to do. If you want otra to contain
the string "Algo mas", then you need to replace that offending line
with something like:
strcpy(otra, p);
or:
strncpy(otra, p, sizeof(otra)-1);
otra[sizeof(otra)-1] = 0;

If, on the other hand, you simply want the character 'A' copied to the
first element of otra (so that otra contains the string "A"), then you
need to replace that line with:
otra[0] = *p;
or:
*otra = *p;
 
S

Shezan Baig

Noah said:
Karl said:
otra
+---+---+---+-- ... ---+---+---+
| A | \0| xx| x xx| xx| xx|
+---+---+---+-- ... ---+---+---+

Where did the NUL in otra[1] come from? I didn't see you assign it...

Unless you did, it isn't there. The printf following would then
possibly segfault. That is usually what happens, but I believe the
results are undefined.

When you say:

char otra[256] = " ";

The null-terminator is added after the space by the compiler.

Hope this helps,
-shez-
 
N

Noah Roberts

Shezan said:
char otra[256] = " ";

The null-terminator is added after the space by the compiler.

So it is, didn't notice that. I certainly would not depend on such.
If you assign just one more character to the array you loose your NUL.
When dealing with char*, which in C++ should be very rare, you should
always assign NUL to the end of the string you are building even if you
expect it to be there already. In fact it is better to just assign NUL
to the entire thing as an initialization process: char otra[256] = {
'\0' }; I think does that, but memset does for sure.
 
S

Shezan Baig

Noah said:
Shezan said:
char otra[256] = " ";

The null-terminator is added after the space by the compiler.

So it is, didn't notice that. I certainly would not depend on such.
If you assign just one more character to the array you loose your
NUL.

I don't think this will compile:

char otra[2] = "abcdef";
 
J

Javier

Noah said:
Eventually you will want to learn arrays, pointers, and all that char*
crap (because it pays to understand it), but for now just focus on
learning the stdlib, which includes such things as vectors and strings.

For instance:

std::string str = "Albino aligator"; // or whatever...
std::string *pstr = &str; // Why? I don't know...
std::string copy = *pstr;


Could someone recommend me a good internet resource with tutorials and
references about C++ ?


Thanks inadvance

J
 
C

Clark S. Cox III

Shezan said:
char otra[256] = " ";

The null-terminator is added after the space by the compiler.

So it is, didn't notice that. I certainly would not depend on such.

Why not? It's well-defined, predictable behavior.
If you assign just one more character to the array you loose your NUL.
When dealing with char*, which in C++ should be very rare, you should
always assign NUL to the end of the string you are building even if you
expect it to be there already.

I'd have to disagree. If you "expect it to be there already", why add
it again? If you don't expect it to be there, then your expectations
are wrong.
In fact it is better to just assign NUL
to the entire thing as an initialization process: char otra[256] = {
'\0' }; I think does that, but memset does for sure.
 
N

Noah Roberts

Clark said:
I'd have to disagree. If you "expect it to be there already", why add
it again? If you don't expect it to be there, then your expectations
are wrong.

Whatever. At any rate, using char* in C++ is unwise unless you have a
very particular need for them. It is simply more work than it is
worth. The previous is a perfect illustration. The stdlib++ string
classes are many times easier to use and are equally more powerful.
The OP is much better off using std::string.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top