user3160866
user3160866

Reputation: 387

Initialization for pointer to an integer array

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?

Upvotes: 1

Views: 139

Answers (5)

P0W
P0W

Reputation: 47784

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;
}

Upvotes: 0

Netwave
Netwave

Reputation: 42678

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.

Upvotes: 1

user2754122
user2754122

Reputation:

Yes it is, you can do like this

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

Upvotes: 0

Idov
Idov

Reputation: 5124

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}

Upvotes: 0

TimDave
TimDave

Reputation: 652

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

Upvotes: 3

Related Questions