1

I have the following doubts in C++. We know that we can initialize the pointer in the time of declaration as follows:

int *p = new int(8)
cout<<*p<<endl;

This will produce the output as 8. Similarly if we declare a pointer to an integer array:

int *p = new int[10];

And this can be initialized as:

p[0] = 7
p[1] = 9;

But is there any way to initialize at the point of declaration?

5 Answers 5

3

Using c++11 you can use brace initialization:

int *p = new int[10] { 7, 9 };  // And so on for additional values past the first 2 elements
Sign up to request clarification or add additional context in comments.

Comments

1

Yo could use the "{}" as follows:

int main()
{
   int *p = new int[10]{1,2,3,4,5,6,7,8,9,10};

   cout << p[7] << endl;
   return 0;
}

The outoput will be 8, corresponding to the position 7 of the array.

Note: it is a c++11 based solution.

Comments

0

Yes, if you'd like to initialize your array to 1,2,3,4 for example, you can write:
int[] myarray = {1,2,3,4}

1 Comment

That's fine unless, as here, you want to allocate the array with new.
0

Yes it is, you can do like this

int *p = new int[3] {4,5,6};

Comments

0

As other said you can use the C++11 list initialization {}

Or you can overload new [] and initialize with an array, something like following :

#include <iostream> 

void* operator new[](std::size_t sz, int *arr)
{
    void* p = operator new[](sz);
    int *ptr= (int *)p;
    std::size_t i=0;

    for(;i<sz;++i)

       ptr[i] = arr[i];

    return p;
}

int main()
{

    int arr[] ={1,2,3,4,5,6,7,8};
    int* p = new( arr) int[8];

    for(int i=0;i<8;i++)
     std::cout<<p[i] << std::endl;

    delete[] p;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.