Dynamic memory allocation

Using pointers to dynamicaly make an array

Page 1 of 1

13 Replies - 1884 Views - Last Post: 03 October 2010 - 09:27 PM Rate Topic: -----

#1 The Blue Phoenix  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 84
  • Joined: 07-March 10

Dynamic memory allocation

Posted 03 October 2010 - 09:10 AM

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
char* saying;
int n;
int x;
int main (/*int nArg, char* pszArgs[]*/)
{
    //attempt to read a string of variable length
    cout << "here goes nothing\n";
    cin>>n;
    cin.width(++n);
    saying = new char[n];
    cout << endl;
    cin >> *saying;
    cout << endl;
    x = n;
    n = 0;
    while (n <= x)
    {
        cout<< *(saying + n);
        n++;
    }
    delete [] saying;
    return 0;
}



I am new to C++ and am attempting to teach myself how to use pointers to create variable length arrays. When i run this program it successfully stores the data from cin to *saying (or at least i think it dose) but when i go to display the content of the array i get the first char returned and then multiple garbage letters. for example "====2z".

i tried changeing line 23 to:
 cout<< *saying; 

and deleting the while loop but then i only got the first letter out.

What could i do to make the program display all of what the user inputs, and i don't want the answer "use #include <string>".

another thing i would like to know is how do i read how long the data is that the user inputs with out storing it in a string and without asking?

any help is appreciated,
thanks
The Blue Phoenix

Is This A Good Question/Topic? 0
  • +

Replies To: Dynamic memory allocation

#2 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Dynamic memory allocation

Posted 03 October 2010 - 09:15 AM

*saying : Explain this expression to us.
Was This Post Helpful? 0
  • +
  • -

#3 The Blue Phoenix  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 84
  • Joined: 07-March 10

Re: Dynamic memory allocation

Posted 03 October 2010 - 09:25 AM

View PostOler1s, on 03 October 2010 - 08:15 AM, said:

*saying : Explain this expression to us.


no offense but i did post that i tried several forms of the code listed above,

Quote

i tried changeing line 23 to:
view source
print?
1 cout<< *saying;

and deleting the while loop but then i only got the first letter out.

if you are going to chide me please at least read what i submitted.

also to answer your question *saying is in reference to the data stored in the location in ram pointed to by the pointer saying. saying points to enough room to store new char[n] where n is the number the user submitted for the first cin statement.

the programs task is quite simple; i want it to take a number from the user, set cin.width to that number + 1 so the whole string will fit, allocate a space in memory for that chunk of data, store it there, and lastly display what was stored. (probably should have been more specific about that.)
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,517
  • Joined: 23-August 08

Re: Dynamic memory allocation

Posted 03 October 2010 - 09:28 AM

Oler1s is NOT chiding you...he's trying to TEACH you by getting you to explain your thought process and then guiding you to discovering why that thought process is wrong.
Was This Post Helpful? 1
  • +
  • -

#5 The Blue Phoenix  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 84
  • Joined: 07-March 10

Re: Dynamic memory allocation

Posted 03 October 2010 - 09:29 AM

View PostThe Blue Phoenix, on 03 October 2010 - 08:25 AM, said:

View PostOler1s, on 03 October 2010 - 08:15 AM, said:

*saying : Explain this expression to us.


no offense but i did post that i tried several forms of the code listed above,

Quote

i tried changeing line 23 to:
view source
print?
1 cout<< *saying;

and deleting the while loop but then i only got the first letter out.

if you are going to chide me please at least read what i submitted.

also to answer your question *saying is in reference to the data stored in the location in ram pointed to by the pointer saying. saying points to enough room to store new char[n] where n is the number the user submitted for the first cin statement.

the programs task is quite simple; i want it to take a number from the user, set cin.width to that number + 1 so the whole string will fit, allocate a space in memory for that chunk of data, store it there, and lastly display what was stored. (probably should have been more specific about that.)


i feel stupid now, that bottom half of your post was your signature, and that whole wall of text was in response to that. sorry for reading your post the wrong way Oler1s and thanks for your post.
Was This Post Helpful? 0
  • +
  • -

#6 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Dynamic memory allocation

Posted 03 October 2010 - 09:47 AM

Quote

no offense but i did post that i tried several forms of the code listed above,
Unless your strategy to programming is randomly throw letters and symbols out and see what sticks, you should be able to explain the syntax of whatever you write. This is your code after all. You did write it. You wrote it for a reason. You believe it follows some syntax. Right? I want you to explain that logic.

For example, if you ask me to explain int a;, I will tell you that this is a variable definition. int is the type in the definition; a is the identifier. Or consider the complicated looking int (*a)(char *); . I will tell you that a is the identifier for a variable. The variable is a pointer. It points a function, based on the syntactical construction. The int indicates the function returns an integer. The (char *) indicates the function takes in a one parameter, of type pointer-to-char.

The above is what I mean by explaining yourself. I don't want to know what you want to do. I want you to explain the syntax and semantics of an expression. I want you to explain the syntax specifically. You haven't quite done that.

Quote

*saying is in reference to the data stored in the location in ram pointed to by the pointer saying.
Too vague. I want you to explain the syntax and semenatics of each part of the expression.

Quote

saying points to enough room to store new char[n] where n is the number the user submitted for the first cin statement.
Doesn't make sense.

Let's look at it this way. Forget all your code, and go through this process. Start with char *saying; . This is a pointer to a char, do you agree? Ok, what is a char? char a; is an example of a char, would you agree? Consequently, you can then have saying point to a, with the statement: saying = &a, yes? saying is a pointer to a char, and now we have pointed it to a single character.

There are now two questions I want you to answer, based on the above argument.

1. What is *saying? We agree that saying is a pointer to a character. What is *saying?
2. Based on my above argument, can you ever say that saying points to something not a character? Or, put it another way. Should you ever be saying something other than "saying points to <a certain> character"?

This post has been edited by Oler1s: 03 October 2010 - 09:58 AM

Was This Post Helpful? 0
  • +
  • -

#7 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • View blog
  • Posts: 2,339
  • Joined: 20-August 07

Re: Dynamic memory allocation

Posted 03 October 2010 - 12:01 PM

To rephrase (slightly) what Oler1s is saying; the focus of your attention here should be the behaviour of the >> operator;

You may or may not be familiar with the notion of overloaded functions - i.e. a function name which has multiple implementations depending on the data type of its arguments. The same rules apply in exactly the same vein to operators, including >>.

(...Yes i am going somewhere with this, hold on a moment)

the C and C++ languages do not give 'pointers' any special treatment, per-se, however the standard libraries do give special-exception treatment to the char* (pointer-to-char) data type (and also to the wchar_t* type for "wide" characters).

Some functions in C and in C++ make the assumption that an argument whose type is pointer-to-char is always a null terminated character array - a.k.a. a "C-string". - in other words, it always assumes that the pointer value resolves to an array belonging to your program (Yes this is an unsafe assumption, but C++ is an unsafe language sometimes).

However, if all you provide is a char argument, then the function will rightly treat the object as if it were a single character variable (if its part of an array, the function will never know about it)

the >> operator is, for the most part, a cute bit of syntactic sugar with a variety of functional overloads which work with std::istream objects (It has other meanings too, but ignore those for now); a few of those overloads are:
std::basic_istream<char>& operator >> (char*);
std::basic_istream<char>& operator >> (char);
std::basic_istream<char>& operator >> (int);
std::basic_istream<char>& operator >> (short);
std::basic_istream<char>& operator >> (double); 
//etc.


The reason for the question of "what is the type of *saying", is simply because the overload which is picked relies solely on the compiler deducing the type of the argument that you are passing;

  • if the operator >> is passed an argument whose data type is int, then the overloaded operator for int will be chosen;
  • if the operator >> is passed an argument whose data type is char*, then the overloaded operator for char* (Which is assumed to be a "C string" will be chosen;
  • and so on..


If you can look at the expression *saying (translation: dereference 'saying') from a compiler's perspective, you can tell exactly which overload of the >> operator is being used; (remembering that the dereferencing operator changes the data type of its operand)

This post has been edited by Bench: 03 October 2010 - 12:17 PM

Was This Post Helpful? 2
  • +
  • -

#8 The Blue Phoenix  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 84
  • Joined: 07-March 10

Re: Dynamic memory allocation

Posted 03 October 2010 - 01:03 PM

OK, *saying is supposed to point to the first character in an array of size n. the user could enter a number by accident but lets ignore this because i am the user and i would never do that.

saying is allocated off of the heap by the expression new and i have assigned n bytes to it.
Ive heard a small amount about overloading operators and i am not quite sure what this has to do with it right now. *saying was dimed as type char*, so I'm not quite sure how the computer could mistake it as something else.

*saying is supposed to be a C-string, and terminate in a null character.

when cin receives a string of characters dose it put all of the characters into the variable or just one?

If cin will accept the above mentioned input will it end in a null? i set cin.width to ++n so it should have enough room for n characters and a null.

I think i have explained *saying now but I'm still not sure, as mentioned before i am still a beginner and am not quite sure if that is all the info you need ask for more if you need it.

Also i think the problem is when i say:
 saying = new char[n] 

that may i have not assigned enough room to *saying.

another issue could be that
 cin >> *saying 

only dumps information into the first byte of information pointed to by saying and not the rest of the space allocated by
 saying = new char[n] 

.
my problem is I'm not quite sure what to say to make you understand what >> operator overload i am using. i have posted my code and i don't know much more than that.

Has the info i have provided helped any?
Was This Post Helpful? 0
  • +
  • -

#9 The Blue Phoenix  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 84
  • Joined: 07-March 10

Re: Dynamic memory allocation

Posted 03 October 2010 - 01:11 PM

also i forgot to say that because i allocated saying off of the heap it dose not have a specific char variable that it points to. it dose not point to & anything. the only way i know how to describe it is that it points to a spot in memory with enough room to store n characters.
Was This Post Helpful? 0
  • +
  • -

#10 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,517
  • Joined: 23-August 08

Re: Dynamic memory allocation

Posted 03 October 2010 - 01:28 PM

No, you're misunderstanding pointers a bit. This

Quote

*saying is supposed to be a C-string, and terminate in a null character.

is patently wrong. saying is the pointer to the C-string (an array of characters intended to be null-terminated). The * is the pointer dereferencing operator. It goes to the location of the memory to which saying is pointing and returns the value there; therefore, it's getting a single CHARACTER, not the CHARACTER STRING you're expecting.

This is an excellent reference on pointers.

EDIT: An example. Let's say that saying contains "All's well that ends well". Here's some code (no dynamic memory allocation though):
const char *saying = "All's well that ends well";

// saying here points to the first character in the constant string which was placed in read-only memory by the compiler/linker.
// The compiler/linker sees this variable as a char * and will print it as such, printing the whole string from where saying is pointing until it finds a null terminator.
std::cout << saying << std::endl;

// Now if we want to print just the first CHARACTER of saying, here is where the dereferencing operator comes into play.
// The compiler/linker sees this value as a CHARACTER, not a character string, and therefore will only print the single character to which saying is currently pointing.
std::cout << *saying << std::endl;


This post has been edited by JackOfAllTrades: 03 October 2010 - 01:35 PM

Was This Post Helpful? 2
  • +
  • -

#11 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • View blog
  • Posts: 2,339
  • Joined: 20-August 07

Re: Dynamic memory allocation

Posted 03 October 2010 - 01:45 PM

View PostThe Blue Phoenix, on 03 October 2010 - 08:03 PM, said:

OK, *saying is supposed to point to the first character in an array of size n.
There is a difference between saying and *saying.

saying is a pointer variable (which is a plain integer variable storing a memory address).
*saying is an expression which yields the result of the * operator (the dereferencing operator) on the saying variable.

If it makes things easier to read, C++ has an alternative way of expressing *saying with the subscript operator: saying[0]

In other words, cin >> *saying; is the same as cin >> saying[0];
- it is first causing saying to be de-referenced; when you 'dereference' a pointer variable, you are directly accessing the object referenced by that pointer; for a pointer-to-char, the referenced object is a char.


If you want to use the char* overload of >>, then pass saying (i.e. the address variable) directly, don't dereference it or do anything else to it.

There are a couple more good links here to help demystify the syntax:

http://www.eternally...t_pointers.aspx
http://www.augustcou...torial/ptr.html
Was This Post Helpful? 2
  • +
  • -

#12 The Blue Phoenix  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 84
  • Joined: 07-March 10

Re: Dynamic memory allocation

Posted 03 October 2010 - 05:09 PM

thanks, guys.
so if i am getting this right, *saying is the same as saying[0] and if i pass something to *saying i am actually passing it to the first element in the array. but if i replace
 cin>>*saying

with
 cin>> saying

i will store all of cin and not just the first charactor, right?
Was This Post Helpful? 0
  • +
  • -

#13 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: Dynamic memory allocation

Posted 03 October 2010 - 05:36 PM

Yes unless you overflow the buffer.
Was This Post Helpful? 1
  • +
  • -

#14 janotte  Icon User is offline

  • code > sword
  • member icon

Reputation: 990
  • View blog
  • Posts: 5,141
  • Joined: 28-September 06

Re: Dynamic memory allocation

Posted 03 October 2010 - 09:27 PM

What you have written is mostly C, not C++.

Are you really attempting to learn about pointers and dynamic memory or are you trying to learn about strings?

Unless you really want to get into the world of pointers you have no need to do most of what you have done. C++ strings will do all that for you more safely and far easier to get your head around. On the other hand if your are interested in dynamic arrays C++provides you the vector that achieves all this with greater safety than what you are doing.

I am not saying that what you are doing is wrong or bad to learn or any of that stuff. Just that it is really a C approach and not a C++ approach. Writing C++ as "better C" is acceptable but, except for learning how C works, is not recommended when people far smarter than you and I have put major effort into making C++ do these things better than you and I can do it by hand.

If you really want to understand how C does these things you might find it more valuable to write your code as C so you get the full C experience.

But, as I say, this is not intended to say in any way you are wrong in what you are doing, just that perhaps there is a slightly better way to go about it (maybe).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1