2

I'm attempting to allocate memory for each entry of the array and initialize the members part1 and part2 to 0.

#include <iostream>
using namespace std;

class Two {
public:
    int part1;
    int part2;
};


int main() {

    Two * dp[10]; //array of 10 pointers to objects of class Two

    part1 = 0;
    part2 = 0;

    for (int i = 0; i < 10; i++) { 
        dp[i] = 0;                        

    }
    return 0; 
}

Any help is appreciated. I'm new to c++ and I'm trying to understand the basic concepts. Thank you in advance!

Alicia Sabatino
  • 57
  • 1
  • 2
  • 10
  • Do you now how to access a class member from an object? – NathanOliver Sep 19 '17 at 19:13
  • 2
    Why not use `std::vector` instead of this array? – tadman Sep 19 '17 at 19:13
  • @tadman I'm trying to understand how to do it with out because generally in class and in tests we aren't allowed std::vector. :( – Alicia Sabatino Sep 19 '17 at 19:14
  • 6
    Nothing will give you understanding of basic concepts better than [time with a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). I *strongly* suggest you get one. – WhozCraig Sep 19 '17 at 19:14
  • Since you're declaring `Two` as a class you should give it a proper constructor that initializes the properties correctly. Also use `NULL` or `nullptr` instead of `0`. – tadman Sep 19 '17 at 19:14
  • Use std::vector, it will properly call your default constructor. Do it without pointers, just pure heap objects. Like std::vector dp(10); – Avi Sep 19 '17 at 19:14
  • What is with these teachers that think they're teaching C++ while ignoring the Standard Library? They're doing more harm than good. If they're so allergic to containers maybe they should be teaching assembly class. – tadman Sep 19 '17 at 19:15
  • 1
    1. I see no dynamic memory allocation here 2. modern C++ relies on standard containers first, smart pointers second, and raw memory allocations a distant last. – crashmstr Sep 19 '17 at 19:15
  • I suggesting [taking a tour of C++11](https://isocpp.org/tour). – R Sahu Sep 19 '17 at 19:15
  • @tadman I agree. The teaching assistants agree as well. We will go into the work force with out proper knowledge of the standard library abilities. – Alicia Sabatino Sep 19 '17 at 19:16
  • My advice is to survive this course as best you can and ignore all their ridiculously out-dated conventions. Teaching people to write code from first principles is educational if done right, but if you do that in production code that's how you hard fail code reviews. To be effective in C++ you have to learn to love the Standard Library, quirks, warts and all. – tadman Sep 19 '17 at 19:18
  • 2
    There's nothing wrong with teaching the basics. How to `new` things, how to `delete` things. A thorough, solid knowledge and understanding of the fundamentals of how objects are managed in dynamic scope is a required skill for every C++ developer. Only once there is good understanding of how to correctly implement arrays, and manual linked list, then you get to move on to `std::vector`, `std::list`, et. al., and use your newly-acquired knowledge to write logically correct code. – Sam Varshavchik Sep 19 '17 at 19:19
  • @SamVarshavchik no, see the talk of Kate Grgory “Stop Teaching C" at cppcon https://m.youtube.com/watch?v=YnWhqhNdYyk –  Sep 19 '17 at 19:24
  • thanks for all the advice everyone! last semester i had surgery and basically skated by the introduction class. I'm trying to get back on track. And yes, as you can imagine trying to do extremely long projects with out vector and other standard library functions is extremely tedious – Alicia Sabatino Sep 19 '17 at 19:26

4 Answers4

5

Here's a really basic version of that code that uses new to allocate memory:

#include <iostream>

class Two {
public:
  Two() : part1(0), part2(0) { };
  int part1;
  int part2;
};


int main() {
  const size_t count = 10;
  Two *dp = new Two[count];

  // Do stuff?

  for (size_t i = 0; i < count; ++i) {
    std::cout << dp[i].part1 << "/" << dp[i].part2 << std::endl;
  }

  delete[] dp;

  return 0; 
}

Note that for a multitude of reasons this is a bad idea, but if you need to side-step the Standard Library because teacher then this is where you go.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 2
    I am here "because teacher". Thanks. Why in the world my assigned project won't allow vectors, I'll never know. – jlsecrest Jul 25 '19 at 09:20
1

In c++ for your example is preferable to have a default constructor that initialize your data and a std::vector to hold objects of your custom class. This will save you a lot of memory handling problems.

class Two {
public:
  Two() : part1(0), part2(0) { };
  int part1;
  int part2;
};


int main() {
    std::vector<Two> twoVec(10);
    return 0; 
}
Rama
  • 3,222
  • 2
  • 11
  • 26
0

You created 10 pointers to instances of Two , but those pointers are not initalized and doesn't point to any instances.

Here is one way to create those instances, store pointers to them in your array, and then set their part1 member to 1 and the part2 member to 2;

for (int i = 0; i < 10; i++) { 
    dp[i] = new Two();
    dp[i]->part1= 1;              
    dp[i]->part2= 2;              

}
nos
  • 223,662
  • 58
  • 417
  • 506
  • 1
    One should not use plain new in modern C++. – Jodocus Sep 19 '17 at 19:21
  • 1
    @Jodocus That's your subjective opinion, and it is not particularly relevant to the question. – nos Sep 19 '17 at 19:22
  • 1
    There is nothing wrong with using `new` in modern C++. – callyalater Sep 19 '17 at 19:23
  • 1
    There is nothing wrong with using new in modern C++ if used correctly, which is harder than one might think, when considering exception safety. Since C++14, there is nothing that can justify the use of raw owning pointers or the use of plain new for allocation. – Jodocus Sep 19 '17 at 19:28
  • Just like `goto` you will find times and places where `new` is exactly the right tool. They may not be common. They may raise eyebrows. They may require some Here Be Dragons comments. But they are out there, lurking in the shadows and ready to strike. – user4581301 Sep 19 '17 at 19:33
-2

You need to allocate objects of the type class Two pointed to by the elements of the array. Otherwise the program will have undefined behavior.

You can do it either using standard algorithm std::generate like this

#include <iterator>
#include <algorithm>

//...

Two * dp[10]; //array of 10 pointers to objects of class Two

std::generate( std::begin( dp ), std::end( dp ), 
               [] { return new Two { 0, 0 };} );    

Or you can use the range based for loop. For example

Two * dp[10]; //array of 10 pointers to objects of class Two

for ( Two * &p : dp ) p = new Two { 0, 0 }; 

Here is a demonstrative program

#include <iostream>

using namespace std;

class Two {
public:
    int part1;
    int part2;
};


int main() 
{

    Two * dp[10]; //array of 10 pointers to objects of class Two

    for ( Two * &p : dp ) p = new Two { 0, 0 }; 

    // processing of the array

    for ( Two * &p : dp ) 
    {
        delete p;
        p = nullptr;
    }       

    return 0; 
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335