How does char arrays works | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does char arrays works

I have some questions about char arrays in this code. Questions are commented. https://code.sololearn.com/cA4a19A8A2A8/?ref=app

1st Jun 2021, 5:45 PM
Adilx01
3 Answers
+ 3
Martin Taylor The quality of your answers keep improving and reinforce concepts I don't typically need to think about as a developer who works primarily with high level languages like C# and Javascript. I just want to say thank you for consistently posting such insightful, rich explanations. Reading your answers alone is worth visiting SoloLearn at least once a day. 👌
2nd Jun 2021, 1:36 AM
David Carroll
David Carroll - avatar
+ 2
1. Since C++11, the standard explicitly forbids implicit conversion and assignment to char*. String literals may be placed in read-only memory, and attempting to modify them would result in undefined behaviour anyway. 2. There is no example of a dynamic char array in your code. Why would you have to allocate memory? 3. Fundamentally, a string literal has the type 'const char[ N ]' with N being the size, and you can't copy-initialize plain arrays directly. The second initialization is valid though. 4. std::cout is overloaded for char pointers to print the referenced string instead of the address. Specifically, it will print characters until a terminating null character is found. To see the address, you need to cast the pointer to a void pointer.
1st Jun 2021, 6:42 PM
Shadow
Shadow - avatar
+ 2
@Martin Taylor Awesome addition! I dug a little bit and in this case it just seems to be MSVC being ahead of GCC. The compiler not being able to deduce the array size from the initializer was deemed an unnecessary inconsistancy in C++ initialization rules and was revised in C++20 (Paper P1009R2). cppreference.com lists this revision being supported by GCC from version 11 on, and version 19.27 for MSVC, see: https://en.cppreference.com/w/cpp/compiler_support/20 Since SL currently uses GCC 10.2.0, it doesn't work here yet. Not sure about the dynamic char array initialization from string literals though.
1st Jun 2021, 7:41 PM
Shadow
Shadow - avatar