473,372 Members | 1,056 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 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 1603
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Ryan Walker | last post by:
Hi, I'm getting started with python and have almost zero programming experience. I'm finding that there are tons of tutorials on the internet -- such as the standard tutorial at python.org -- that...
6
by: Kalle Anke | last post by:
Those who have read my posts today have probably understood that I'm not a "true" Python programmer ... but I want to learn more (I think that Python is rather fun). I've read "Learning Python"...
8
by: Mantorok | last post by:
Hi all I'm looking to learn C and/or C++ and I was wondering if there were any good on-line resources and books. I am currently a C# developer but I'm keen to discover C/C++ as I feel it...
17
by: Karsten Kvistad | last post by:
Hi! I'm currently teaching myself the C programming language. The problem is I don't know what to do next. I know file I/O, pointers, functions and the like. I do not know how to make .h files,...
1
by: ketema | last post by:
Hello, I was wondering if someone could help me with a function I am trying to write. The purpose of the function is to read in text from a file in the following format: FIRSTNAME LASTNAME...
4
by: Andy | last post by:
Hi I'm in the position where my employer might pay for courses in VB.net or even the complete MCAD certification. But I need some good arguments for learning VB.net that can relate to my current...
36
by: utab | last post by:
Dear, I have experince in C( numerical projects, like engineering problems, scientific applications) I have the basic notion of C++ also, I have read Accelerated C++ until Chapter 7, however it...
26
by: mfasoccer | last post by:
I am sorry if this is an inappropriate place to put this post, if so please delete it. I am wondering about a few things. Do you guys recommend learning C as a second language, as someone who...
6
by: JoeC | last post by:
I understand the basics of pointers, they point to memory locations. I would like to know resources for learning all about poters. I am having some problems erasing elements of pointers from a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.