Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int* ptr_arr_int = {1,2}; not work in C/C++?

Tags:

c++

c

pointers

Why does int* ptr_arr_int = {1,2}; gives a compiler error, but whereas char* ptr_arr_char = "amruth"; compiles fine?

int* ptr_arr_int = {1,2};         // ->ERROR
char* ptr_arr_char = "amruth";    // ->OK
like image 585
Amruth A Avatar asked Jul 02 '19 09:07

Amruth A


1 Answers

"amruth" is a const char[7] type in C++, and a char[7] type in C (although the behaviour on attempting to modify the string is undefined).

This can decay to a const char* or char* type respectively in some circumstances, such as yours.

Although an int[2] will similarly decay to an int* in some circumstances, {1, 2} is neither an int[2] nor a const int[2] type; rather it is a brace-initialiser.

like image 181
Bathsheba Avatar answered Oct 25 '22 12:10

Bathsheba