0

creat a pointer in struct creat array initialize -1, 10 times using for loop and print -1, 10 times using method in struct.

struct hasha {
    int* arr;
    int l;
    hasha(int no) {
        arr[no];
        l = no;
        for (int i = 0; i < l; i++) {
            arr[i] = -1;
        }
    }
    void print() {
        for (int i = 0; i < l; i++) {
            cout << arr[i] << " ";
        }
    }
};
int main() {
    hasha a(10);
    a.print();
}
vishal singh
  • 41
  • 1
  • 5

2 Answers2

1

I assume this is for learning purposes, otherwise you should be using a std::vector<int> for this.

struct hasha {
    int* arr;
    size_t l;                // size_t is an unsigned int type better suited for sizes

    hasha(size_t no) :       // use the member initializer list (starting with ":")
        arr(new int[no]),    // create the array
        l(no)
    {
        // initialize the array with -1, "l" times using a for loop
        for (size_t i = 0; i < l; ++i) {
            arr[i] = -1;
        }
    }

    // You need to delete the implicitly declared copy ctor and copy assignment operator
    // to forbid copying hasha objects to not free the `int*` multiple times later.
    hasha(const hasha&) = delete;
    hasha& operator=(const hasha&) = delete;

    // You need a destructor to free the memory you allocated:
    ~hasha() {
        delete[] arr;
    }

    void print() {
        for (size_t i = 0; i < l; ++i) {
            std::cout << arr[i] << " ";
        }
    }
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
-1

The following constructor initialises the pointer with an array: hasha ::hasha (int a[]) : arr (a) {}