This declaration is very confusing:
char* q {new char[1024]{}}; // q[i] becomes 0 for all
Is this a “pointer to a char
array”, or an “array of char
pointers”?
I think that new char[1024]{}
is initializing a char
array of 1024 elements each having a value of 0
.
So this is the same as:
char* q = [0,0,....] // until 1024
Correct?
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Initialization: Assigning a value to a variable is called initialization. For example, cost = 100. It sets the initial value of the variable cost to 100. Instantiation: Creating an object by using the new keyword is called instantiation.
char* q {new char[1024]{}};
is equal to
char* q = new char[1024]{};
which in turn is equal to
char* q = new char[1024] { 0, 0, 0, 0 /* 1020 more zeros */ }
q
is a pointer to a char
. In other words, it is of type char *
.
It is initialised using the expression new char[1024]{}
which dynamically allocates an array of char
and zero-initialises them. If this fails, an exception will be thrown.
q
will point to the first char
in the dynamically allocated array. It is not an array.
It is not the same as
char* q = [0,0,....] // until 1024
since that is invalid syntax. It is also not equivalent to
char* q = {0,0,....}; // 1024 zeros in initialiser
since q
is a pointer and cannot be initialised to a set of values. It is closer in (net) effect to
char *q = new char[1024]; // dynamically allocates chars uninitialised here
std::fill(q, q + 1024, '\0');
except that the characters are initialised to zero, rather than being first uninitialised and then overwritten with zeros (and, of course, it is up to the compiler how it initialises the characters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With