1

So, I was trying to learn pointers from scratch and I hit up on this. I tried doing the following:

void func(int* ptr){
  //Yada-yada
}
int main(){
  int a[] = {1,2,3,4,5};
  func(a);
}

which worked out great. But then, I tried to do the following:

void func(int* ptr){
  //Yada-yada
}
int main(){
  int a[] = {1,2,3,4,5};
  func({1,32});
}

which returned an error saying

too many initializer values So I replaced it with

func({1});

which ended up with

a value of type "int" cannot be used to initialize an entity of type "int *"

So I'd like to know why this happens. Does the compiler not allocate space for an array that is not being used as an rvalue for a variable?? Because if it does, the expected result would be that ptr is passed the address of the first variable in either of the {1,32} or {1} cases.

Thanks in advance. P.S : Only reply to this if you intend to help. If you have comments to tell me to go read a book or something, I already am. But to the ones who actually want to be helpful, links to references are very much appreciated.

4
  • 2
    {1,32} is a std::initialized_list<int>, which is not convertible to an int *. Commented Oct 24, 2020 at 20:12
  • read about std::initializer_list Commented Oct 24, 2020 at 20:17
  • 6
    {1,32} is not an array. It doesn't have a type at all according to the C++ language specification. It's a syntactic construct that can be used to initialize objects. Sometimes, the properties of the object can be deduced from it, but those are the exceptions, not the rule. Commented Oct 24, 2020 at 20:17
  • @StoryTeller-UnslanderMonica you should post as answer. Commented Oct 25, 2020 at 2:50

1 Answer 1

5

{1,32} is not "an actual array". It is a brace enclosed list of initialisers. The pointer parameter cannot be initialised with such list unless the list contains exactly one initaliser of a type that is convertible to the pointer.

Sign up to request clarification or add additional context in comments.

1 Comment

So, the 2nd case fails because a initializer list with multiple items is not compatible in general. The 3rd case fails instead because the list with 1 item would be compatible if the contained int would be compatible but it isn't. (The OP was lucky that the last snippet contained { 1 } but not { 0 } which had caused even more confusion.)

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.