1

When I try to run the following

// Example program
#include <iostream>
#include <string>

int* x;

int main()
{
  x = (int[5]) { 16, 2, 77, 40, 12071 };

  std::cout << x;
}

I get the following message error: taking address of temporary array

What does this mean?

AlanSTACK
  • 5,525
  • 3
  • 40
  • 99

1 Answers1

6

(int[5]) { 16, 2, 77, 40, 12071 } is an anonymous temporary. It goes out of scope once the assignment is complete.

That leaves you with a dangling pointer. It makes no difference that x is in the global namespace.

Use std::vector instead; taking advantage of initialiser-list construction.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • What do you mean out of scope? I thought c++ does not have a garbage collector? – AlanSTACK Oct 02 '17 at 07:48
  • 3
    Worth mentioning for those familiar with C. If we remove the C++ includes and fix the prototype of main. This becomes a compound literal. And it lives for the duration of the enclosing scope. Another fun difference between the two cousin languages. – StoryTeller - Unslander Monica Oct 02 '17 at 07:48
  • 3
    @Alan - You don't need a garbage collector to have scoping. A good [book about C++](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should explain. – StoryTeller - Unslander Monica Oct 02 '17 at 07:49
  • 1
    @StoryTeller: You're in my pub quiz team. – Bathsheba Oct 02 '17 at 07:49
  • @Alan end of scope has immediate and deterministic implicit effect of releasing everything what belonged to that particular scope, while garbage collector is some external random event, maybe happening somewhere in the future, if ever. Which makes resource management in C++ very convenient and easy, as you can exactly say when is what released, and you can write your code in a way to make it happen when you need it. Although if you for some weird reason lack the randomness of GC, there are of course C++ libraries implementing GC, so it's not like it doesn't exist for C++, just not part of std. – Ped7g Oct 02 '17 at 08:57