472,126 Members | 1,569 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,126 software developers and data experts.

Learning pointers in C++


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

Jul 23 '05 #1
17 1524
Javier wrote:

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.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #2
you will need to do char * p = &algo;

greets
Javier wrote:
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


Jul 23 '05 #3
qolume wrote:
you will need to do char * p = &algo;

No he does not. Not only won't that help, the program won't
be well-formed after that.
Jul 23 '05 #4

Javier wrote:
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-


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


Jul 23 '05 #5
Karl Heinz Buchegger wrote:
Javier wrote:
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
Jul 23 '05 #6

Javier wrote:
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-

Jul 23 '05 #7
Javier <jl****@manresa.net> writes:
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;
}
-----

The FAQ (http://www.parashift.com/c++-faq-lite/) covers References
and much else besides.
Jul 23 '05 #8

Karl Heinz Buchegger wrote:
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.

Jul 23 '05 #9
On 2005-02-03 07:37:03 -0500, Javier <jl****@manresa.net> 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 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;

--
Clark S. Cox, III
cl*******@gmail.com

Jul 23 '05 #10

Noah Roberts wrote:
Karl Heinz Buchegger wrote:
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-

Jul 23 '05 #11

Shezan Baig wrote:
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.

Jul 23 '05 #12

Noah Roberts wrote:
Shezan Baig wrote:
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";

Jul 23 '05 #13
Noah Roberts wrote:

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
Jul 23 '05 #14

Javier wrote:
Noah Roberts wrote:
>
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++ ?

http://mindview.net/Books
http://search.barnesandnoble.com/boo...60&TXT=Y&itm=1

Jul 23 '05 #15

Javier wrote:
Noah Roberts wrote:
>
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++ ?
http://search.barnesandnoble.com/boo...60&TXT=Y&itm=1
http://mindview.net/Books

Thanks inadvance

J


Jul 23 '05 #16
On 2005-02-03 12:46:22 -0500, "Noah Roberts" <nr******@stmartin.edu> said:

Shezan Baig wrote:
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.

--
Clark S. Cox, III
cl*******@gmail.com

Jul 23 '05 #17

Clark S. Cox III wrote:
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.

Jul 23 '05 #18

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Ryan Walker | last post: by
6 posts views Thread by Kalle Anke | last post: by
8 posts views Thread by Mantorok | last post: by
17 posts views Thread by Karsten Kvistad | last post: by
36 posts views Thread by utab | last post: by
26 posts views Thread by mfasoccer | last post: by
6 posts views Thread by JoeC | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.