initialize a new pointer to an existing array

Please tell me how to initialize a new pointer to an array after the array has already been created:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<array>

struct Card
{
	int value = 0;
};

int main()
{
	std::array<Card,52>card_deck;
	Card * nptr = card_deck;

	for (int itr = 0; itr<card_deck.size(); ++itr)
	{
			//stuff
	}

}


error:

..\src\main.cpp:12:16: error: cannot convert 'std::array<Card, 52ull>' to 'Card*' in initialization
I see you're using the std::array type.

To get a pointer to the first element, use the class function data.

http://www.cplusplus.com/reference/array/array/data/
Hi,

To realise why your original code didn't work: a std::array does not decay to a pointer like an ordinary array does.
I thought that as well. This was a posted example of using a pointer to an std::array, if that's what it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<array>

struct Card
{
	int value = 0;
};

void printCard(Card *cardPtr)
{
	std::cout<<cardPtr->value<<std::endl;
}

int main()
{
	std::array<Card,52>card_deck;
	card_deck[0].value = 70;
	card_deck[1].value = 50;
	Card *cardPtr = &card_deck[0];
	printCard(cardPtr++);
	printCard(cardPtr++);
	for (int itr = 0; itr<card_deck.size(); ++itr)
	{
			//stuff
	}

}


Set the pointer to card_deck[whatever in bounds number] & go from there. I was taught as well that std::array does not decay into pointer and shouldn't be used in pointer environment.
Last edited on
Topic archived. No new replies allowed.