Skip to content

Use of Pointers For Lists

Here’s List.h

#ifndef LIST_H
#define LIST_H

class List {
public:
    List();  // Constructor
    ~List();  // Destructor
    void addItem(int item);  // Add integer item
    void deleteItem(int loc);  // Delete item

private:
    int *ptr = nullptr;
    int size = 0;  // Pointer and its size
};

#endif

Here’s the List.cpp

#include "List.h"
#include <stdexcept>

List::List() {
    // The constructor initializes size to 0 and ptr to nullptr
}

void List::addItem(int item) {
    int *newPtr = new int[size + 1];
    for (int i = 0; i < size; i++) {
        newPtr[i] = ptr[i];
    }
    newPtr[size] = item;
    delete[] ptr;
    ptr = newPtr;
    size++;
}

void List::deleteItem(int loc) {
    if (loc < 0 || loc >= size) {
        throw std::out_of_range("Index out of range");
    }

    int *newPtr = new int[size - 1];
    for (int i = 0; i < loc; i++) {
        newPtr[i] = ptr[i];
    }
    for (int i = loc + 1; i < size; i++) {
        newPtr[i - 1] = ptr[i];
    }
    delete[] ptr;
    ptr = newPtr;
    size--;
}

List::~List() {
    delete[] ptr;
}

Oh hi there 👋 It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam!

2 Comments

  1. bk bk

    Are you sure the “delete[], delete” thing is not wrong? Something tells me this is a double delete on the same pointer. Also, this class could benefit if you allocated memory in chunks (have a “size” member and “allocated_size”, allocate e.g. 1024 bytes more when when “size” >= “allocated_size” and vice versa when freeing memory).

  2. Yusuf Aytaş Yusuf Aytaş

    Thank you very much for your attention. The first delete [] ptr is to delete array elements. The second one is not necessarry and we delete ptr. Yout are right about “size” and “allocated_size”. However, I wanted to show people the use of pointers and I did not care about efficiency. It will be more beneficial if we use chunks.
    Thank you very much…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.