0

I am struggling a little bit with a project I have and am in need of some serious help. For now, I just want to be led on the right path and will follow up with any more questions I have regarding the project. Also, I am using Visual Studios. :)

Alright, so I am supposed to implement a list class within a namespace lib. This is all supposed to be defined within a header file. The list class will implement a variable-sized array where memory management within the class methods will be performed. The list class shall contain the private member double* _data which will be the array of floating point values.

The list must be default constructible. This constructor shall set list::_data equal to nullptr and the size of the list to 0 (there is no data stored). The list must also be constructible with a parameterized constructor accepting an unsigned integer parameter (reference as N herein) denoting the intended size of the array. The constructor shall allocate an array of size N and set the size to be N.

I'm fairly new to C++, so I am still trying to wrap my head around everything. However, here is my header file so far:

#ifndef LIST_H
#define LIST_H

namespace lib {
    class list {
    private:
        double* _data;
        list() {        //default constructor
            list::_data = nullptr;
        }

        list(unsigned int n) {      //contructor
            //array size = unsigned int n

        }
    };
}

#endif
#pragma once

I want to make sure I am on the right path so far, but need help allocating memory. Any help is appreciated. :)

2 Answers2

0

In C, to dynamically allocate memory use malloc and then free the memory after you are done with it.

_data = (double*) malloc(n * sizeof(double));

When and why to use malloc?

How do free and malloc work in C?

You can free the data in the list deconstructor

~list() { free(_data); }

In c++ you also have access to new and delete.

https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/

_data = new double[n];
~list() { delete[] _data; }
0

It looks like you are building a linked list. This page shows a basic linked list setup if you get stuck: https://www.learn-cpp.org/en/Linked_lists

Also, if you need to have a separate header and .cpp file

the header definitions would look like:

list(); or void add(double n);

the .cpp implementations would look like:

list::list() {//constructor} or void list::add(double n) {//add to list stuff}

jmnSnow
  • 5
  • 4