Dynamic memory and Arrays

Hi all,

I'm working on another assignment, and I'm in need of some help with dynamic memory and arrays.

As of right now I have the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <new>
#include <cstdlib>

using namespace std;

int main()
{
    int *i = new int;                  //declare dynamic memory for variable i as an integer
    *i = 4;                            //Arbitrary value assigned to the int

    cout << "Int @ " << & *i << " = " << *i << endl;
      cout << endl;
        system("Pause");
            cout << endl;

    long *l = new long;                //declare dynamic memory for variable l as a long
    *l = 8;                            //Arbitrary value assigned to the long

    cout << "Long @ " << & *l << " = " << *l << endl;
      cout << endl;
        system("Pause");
            cout << endl;

    char *c = new char;               //declare dynamic memory for variable c as a char

    float * f = new float [100];
         for ( *f = 100; *f < 200; *f++);

    cout <<"The array output is: " << *f << endl;
    cout <<"The address in memory of the float is: " << & *f << endl;

    cout << endl;
    system("Pause");
    cout << endl;

  return 0;

  };


The outputs for the arrays will need to mimic my "int" and "long" code segments.

First I need to create is an array of 100 floats, starting at 101 and counting sequentially.

I've populated arrays before in similar to this but never with pointers and references, or using a float. I'm becoming confused because I usually use "int i" to build my array. I've researched it and using the "new" command while simple is confusing when it comes to incrementing an array (and populating it).

What I need help with is a rough idea of how to develop an array that can start at line 100 (with the number 101 populated into it) and to increment it 100x, while still being able to report the address.

I also need to create an array of chars (100). It will need to be populated with a-z and then A-Z, then cycling back until the array is populated. I haven't started this part yet in the code above because I am not sure if there is a function for "counting" through the alphabet like that or if I'll manually need to populate line 0 through 99.

A classmate's example in our course forum has output looking like this for the arrays:
"Char @ A112039 = A " 
"Float @ B112039 = 101 


(example output of the first lines for each array)

where the A112039 is the address of the Character entry and B112039 is the address of the float entry.

I'm still learning C++ so I may not understand a term or two at first pass, please forgive me ahead of time. Eventually I'll build a delete functions into the code as well, but that's a later step.
Not sure if this is allowed, but I read the terms for the forum and didnt see it listed. Small bumpity.

It's not the array creation that I need help with, it's which variables need to have the addressing applied and which don't in the array construction so that I can output each lines address.

and also how to "count" in letters. Do I need to create a string and write out a-z, A-Z 100x or is there a function that will increment letters? (like you do with ints). My google searches keep describing input strings from a user. :(
There are lots of ways to work with arrays and pointers. Here's an example:
1
2
3
4
5
6
7
8
9
    const int size = 100;
    float * f = new float [size];
    *f = 100;                              // assign value to first element.
    for (float * p = f+1; p < f+size; ++p) // loop through array
        *(p) = *(p-1) + 1;                 // assign each element in sequence
    
    cout << "The array contains:\n";
    for (int i= 0; i< size; ++i)           // Loop to display array contents
        cout << f[i] << ' ';


Also, some of your code was using a convoluted sequence of dereferencing the pointer, and then taking the address of the resulting value. You could just use the pointer directly.
 
cout << "Long @ " << & *l << " = " << *l;
could be simply
 
cout << "Long @ " << l << " = " << *l;



and also how to "count" in letters.
Not sure what you mean exactly. However, internally a char is stored as an 8-bit signed binary integer, and you can add and subtract or increment/decrement char variables using ++ and -- just like an ordinary int.


Last edited on
Cheers chervil!

For the simplification part, excellent! I kinda was dancing around that in my float array but hadn't realized the link there yet (you'll see what I mean below). I've made those changes.

For the float array, I tried that code and compiled it. It works, and looks nice (I didn't know you could make arrays look like that) but it doesnt' display the addresses in the output as needed.

For instance that code looks like:

100 101 102 103 104 105 106 107......149
150 151 152 153 154 155 156 157.......200


After posting earlier, I played around and did even more research and made a bit of headway.

I've got:
1
2
3
4
5
6
7
8
9
10
11
   //Float Array
    float * f = new float [100];
    f = new float;                // dynamically allocate a float and load address into f

    for(float f = 101; f < 201; f++)
    {
    cout <<"Float @ " << & f << " = " << f << endl;
      cout << endl;
        system("Pause");
            cout << endl;
    }


Which gives me the proper "output" format of:

Float @ 0x100 (made up hex address) = 101
(press enter to continue)

Float @ 0x100 (same as above) = 102
(press enter to continue)

Float @ 0x100 (same as above) = 103
(press enter to continue)

Float @ 0x100 (same as above) = 104
(press enter to continue)

etc.


Which is what I am supposed to have. My issue now is, shouldn't the address of the memory increment for each line? For instance, all 100 lines of my array have exactly the same address and I'm not sure if they are supposed to grow with each line in the array. Like shouldn't the pointer/reference (whichever it is I've used) move one memory slot up with each line?

As for the char array, it should be similar to the float in that it increments the same way, listing the memory for each line except the output reads = "a" and go "b", "c", "d"... "z", and then start again at "A", "B", "C", "D"... "Z" and then start again at lower case "a" -- continuing until it gets through 100 lines, as compared to 101, 102, 103, 104, etc. in the float. I think what you've provided is exactly what I meant (for incrementing), but I've read that when you hit "z" there is an issue, and I wouldn't be sure how to cycle over to the capitals from "z" - "A".
Last edited on
My issue now is, shouldn't the address of the memory increment for each line? For instance, all 100 lines of my array have exactly the same address and I'm not sure if they are supposed to grow with each line in the array.

This code is broken, badly broken.
1
2
3
4
5
6
7
8
9
10
11
   //Float Array
    float * f = new float [100];
    f = new float;                // dynamically allocate a float and load address into f

    for(float f = 101; f < 201; f++)
    {
    cout <<"Float @ " << & f << " = " << f << endl;
      cout << endl;
        system("Pause");
            cout << endl;
    }

Line 2: allocate memory for 100 floats. Store the address of that block of memory in the variable f.

Line 3: f = assign some other value to f.
What has just happened? You've made sure that the array allocated on the previous line can never be accessed, because the address was overwritten with some other value. That means there is also a memory leak. Every time new is used, there should be a corresponding delete. Similarly, every new [] should have a corresponding delete [] (note the square brackets on the delete).

Because the address was thrown away, it isn't possible to use delete [] f; to release that memory when we're done. (Though when the program ends the memory is properly given back to the operating system, even if there are errors in the program itself).

As for the loop at lines 5 to 11, that introduces a completely separate variable, rather confusingly it is also given the name f although it has nothing at all to do with the previous use of f.


Take a look at this, it may be closer to your requirements, and properly releases the memory at the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
    float * f = new float [100];            // allocate memory for 100 floats
    
    for (int i=0; i<100; ++i)               // loop to assign values from 101 to 200
    {
        f[i] = i + 101;
    }
    
    for (float * p = f; p < f+100; p++)     // use a pointer to step through the array
    {
        cout << "Float @ " << p             // print the address stored in the pointer
             << " = " << *p << '\n';        // and the value which it points to.
    }
    
    delete [] f;                            // release the memory when we're finished with it.
}


Wow, looking at it, it seems so simple. I was on the right path but as you say butchered it completely.

You have exactly nailed it chevril. I hadn't written in the deletes yet, but that was the only part I "knew". I guess my problem was that I screwed up when I tried using line 7 the first time on my own, and thus ended up shoe horning other loops I had built for other questions in.

I had also allocated "i" to another global variable earlier but that was an easy fix. Thank you for your help (I always appreciate when people add the comments so I can figure it out too and see how it breaks down so cheers for that - not only did you help but taught me a thing or two).

I also think I will be able to build off this to get the char array working based on your earlier input, although I am still unsure how to go from "z' to capital "A" when incrementing chars.

Also for the deletes do you recommend deleting them as soon as they are done or at the end of the program? I can't tell when since most things say "after".

For instance I have a
1
2
3
4
5
//Integer
    int *n = new int;                  //declare dynamic memory for variable i as an integer
    *n = 4;                            //Arbitrary value assigned to the int

    cout << "Int @ " << n << " = " << *n << endl;


Is it best to implement the delete after this reports it's value in the output, or at the end of the entire program? For the float array, that is the last part of the program, so delete [] f; will be at the end no matter what, but do I put my other deletes there or after their sections to release the memory for the next section?
Last edited on
Also for the deletes do you recommend deleting them as soon as they are done or at the end of the program? I can't tell when since most things say "after".

There's no real answer to this, the important thing is to make sure it doesn't get forgotten, so doing it as early as possible could be considered a way to make it less likely to get overlooked.

However, there's one other point. If you have a pointer which has been used, you're done with it, but that variable is still accessible throughout the rest of the program, something else could accidentally try to make use of it, which would be a big no - no.
It is usual to set a pointer to a null value after deletion.
1
2
    delete [] a;
    a = nullptr;

That does give some protection against accidental misuse.

It will need to be populated with a-z and then A-Z, then cycling back until the array is populated.
I am still unsure how to go from "z' to capital "A" when incrementing chars.

I'm sure there are a lot of different answers to this. I think the important thing is that the array elements will be accessed in the usual way, going up in steps of 1 each time. It is only the value to be stored which will be changing in a different way. You might perhaps make use of some if-else statements in a creative way.

Thanks again Chervil (I've been typing Chevril, oops!).

For this program I guess its fine if they're all in a segment at the end together, but I like your advice. As I move into bigger and "deeper" programs (ie. more than just 50-100 lines of code), I'll definitely use your suggestion for the null value after deletion. The whole reason I switched to an IDE (we were using cygwin + command prompt which is okay but frustrating for debugging) was because issues similar to this can be hard to catch in bigger programs. Got to love the colour coding and logs.

Also for the chars, I'll spend the next day or two seeing just how "creative" I can be with the char array. If I struggle I'll post again but thanks for giving something to build off and attempt on my own.

Cheers and happy holidays.
Last edited on
By the way, at some point you'll probably run into an issue where the cout << starts treating your char pointer as though it was a string. When/if that happens, don't panic.

You may need to 'cast' the char pointer to a different type, a void pointer.
http://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value

Merry Christmas!
I think I've run into that already a few times, where it outputs just a string of randomly depleting lines (like the first line is 60+ characters, the next line is 59, the next line is 58, etc) until it self terminates.

I'll try applying the casting "const" and see how that goes, but I gotta read up on using it properly first. Cheers for the link!
Topic archived. No new replies allowed.