Posts

Showing posts from April, 2019

Dynamic Memory allocation in C++ for 1d, 2d and 3d array

#include <iostream> #define N 10 // Dynamically Allocate Memory for 1D Array in C++ int main() { // dynamically allocate memory of size N int* A = new int[N]; // assign values to allocated memory for (int i = 0; i < N; i++) A[i] = i + 1; // print the 1D array for (int i = 0; i < N; i++) std::cout << A[i] << " "; // or *(A + i) // deallocate memory delete[] A; return 0; } //2-Dimentional Array. // using single pointer; #include <iostream> // M x N matrix #define M 4 #define N 5 // Dynamically Allocate Memory for 2D Array in C++ int main() { // dynamically allocate memory of size M*N int* A = new int[M * N]; // assign values to allocated memory for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) *(A + i*N + j) = rand() % 100; // print the 2D array for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) std::cout << *(A + i*N + j) << "

Write Your Own String Class:

class OwnString { private : char *string1 = NULL; int size; public: OwnString(void) { string1 = NULL; } OwnString(const char * strData) { size = strlen(strData); string1  = new char[size + 1]; int i = 0; while (*strData) { string1[i] = *strData; strData++; i++; } } OwnString & operator=(OwnString & obj) { if (this != &obj) { delete[]string1; size = obj.size; string1 = new char[size+1]; int i = 0; while (i<size+1) { string1[i] = obj.string1[i]; //strData++; i++; } } return *this; } OwnString (const OwnString & obj) { if (this != &obj) { delete[]string1; size = obj.size; string1 = new char[size + 1]; int i = 0; while (i < size + 1) { string1[i] = obj.string1[i]; //strData++; i++; } } } void print() { for (int i = 0; i < size; i++) { cout << string1[i]; }