Home > Software design >  dynamic allcocation object and int c
dynamic allcocation object and int c

Time:03-01

hello I have a doubt how does the code below works??

#include <iostream>
using namespace std;

int main()
{
    int* arr = new int;
    arr[0] = 94;
    arr[1] = 4;
    cout << arr[0] << endl;
}

and why does this shows me a error what should I do

#include <iostream>
using namespace std;

struct test 
{
    int data;
};
int main()
{
    test* arr = new test;
    arr[0] -> data= 4;
    arr[1] -> data= 42;
    cout << arr[0]->data << endl;
}

CodePudding user response:

In your code:

#include <iostream>
using namespace std;

int main()
{
    int* arr = new int;
    arr[0] = 94; // This will work
    arr[1] = 4; // This will cause undefined behaviour
    cout << arr[0] << endl;
}

Int the above code, arr is a pointer to a single int, so you can access that one int using either:

arr[0]
*arr

..but arr1 won't work as there is not enough memory allocated for the array.

To fix this, you must allocate more memory for arr:

int* arr = new int[2];

..and to change the size of arr:

int arr_size = 2;
int* arr = new int[arr_size]; // size of arr = 2
arr[0] = 12;
arr[1] = 13;

int* new_arr = new int[arr_size   1];

for (int i = 0; i < arr_size; i  )
{
    new_arr[i] = arr[i];
}

delete[] arr;
arr = new_arr;

// size of arr = 3

But all of this gets computationally expensive and time-consuming when arr has a huge number of elements. So I recommend using C 's std::vector:

Your 2'nd program using std::vector:

#include <iostream>
#include <vector>

struct test
{
    int data;
};
int main()
{
    std::vector<test> vec{ test(4), test(42) };

    std::cout << vec[0].data << std::endl;
}

For more info on std::vector, click here.

Also, consider not using the following line in your code:

using namespace std;

..as it's considered as bad practice. For more info on this, look up to why is "using namespace std" considered as bad practice.

  • Related