0x00 And Char Arrays - C++ - Stack Overflow
-
- Home
- Questions
- Tags
- Users
- Companies
- Labs
- Jobs
- Discussions
- Collectives
-
Communities for your favorite technologies. Explore all Collectives
- Teams
Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
Try Teams for free Explore Teams - Teams
-
Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about CollectivesTeams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about TeamsGet early access and see previews of new features.
Learn more about Labs 0x00 and char arrays Ask Question Asked 12 years, 11 months ago Modified 12 years, 11 months ago Viewed 20k times 0Why do char arrays stop right before a 0x00 byte is detected and how can this problem be avoided (perhaps by using another datatype (which one and why) or a "trick" with char)?
For example in the following code, the output is "a" only, the other bytes are not displayed:
unsigned char cbuffer[]={0x61,0x00,0x62,0x63,0x0}; std::string sbuffer=reinterpret_cast<const char*>(cbuffer); cout << sbuffer << endl;Similarly in the following code, the output is "ab":
unsigned char cbuffer[]={0x61,0x62,0x00,0x63,0x0}; std::string sbuffer=reinterpret_cast<const char*>(cbuffer);Straightforward and effective workarounds to the problem (where 0x00 is kept in the array as a normal byte) would be appreciated.
Share Improve this question Follow asked Dec 14, 2011 at 19:09 Chris SmithChris Smith 7641 gold badge9 silver badges22 bronze badges 3- 4 Ummm. Because strings in C are arrays of char terminated with a zero byte? – Heath Hunnicutt Commented Dec 14, 2011 at 19:10
- std::vector with overloaded operator << (ostream&, const vector<char>&). – moshbear Commented Dec 14, 2011 at 19:16
- @HeathHunnicutt: Not necessarily. It's not uncommon to not use trailing zeros. The language itself only requires it for string literals. The libraries may also require it, but that's not the same thing. – Mooing Duck Commented Dec 14, 2011 at 19:18
6 Answers
Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 6It's common in C to pass around strings as pointers to null-terminated char arrays. null is represented by 0x00. To make conversion easy, the std::string is constructable from a pointer to a null-terminated char array, which is what is happening with your code. But when it finds the null, it thinks that's the end of the string. If you cout a char array directly, you'll find it makes the same assumption, because they have no other way to determine the end of a string pointed to by a char*. (They could theoretically tell the length in your case, if they understood char (&)[], but almost nothing in the standard library does sadly).
The intended workarounds are to use this constructor instead:
int len = sizeof(cbuffer)/sizeof(cbuffer[0]); std::string sbuffer(cbuffer, len); //5 characters in cbuffer, 1 byte eachor
int len = sizeof(cbuffer)/sizeof(cbuffer[0]); std::cout.write(cbuffer, len); //5 characters in buffer, 1 byte eachHowever, you have to be careful with sizeof(cbuffer). If cbuffer is a char* (pointer) instead of a char(&)[] (array), then sizeof(ptr) will return the wrong value, and there is no way to get the correct length at that point, if the string is not null-terminated.
Share Improve this answer Follow edited Dec 14, 2011 at 21:29 answered Dec 14, 2011 at 19:15 Mooing DuckMooing Duck 66.6k19 gold badges103 silver badges165 bronze badges 11- 1 This is good except for not advocating usign sizeof to determine the buffer length. – Mark B Commented Dec 14, 2011 at 19:26
- @MarkB: I actually had that at first, but then removed it, because of the common "why does sizeof(ptr) return 4, I have 10 letters!". I'll edit the answer to describe the pros and cons. – Mooing Duck Commented Dec 14, 2011 at 19:27
- @curiousguy: What? Do you think my terminology/spelling is incorrect? – Mooing Duck Commented Dec 14, 2011 at 19:31
- @Mooing Duck. Your spelling is incorrect. NULL is a pointer and NUL is a character. – Heath Hunnicutt Commented Dec 14, 2011 at 19:38
- @HeathHunnicutt: Wikipedia disagrees: en.wikipedia.org/wiki/Null_character. NULL is the name of the character. It's commonly abbreviated as NUL however. – Mooing Duck Commented Dec 14, 2011 at 19:39
char arrays don't do anything
The C string functions use 0 to mark the end of a string. std::cout is overloaded for char arrays to print them as 'c' strings, if you want to print individual values you need to loop over the values, you might also want to output them as std::hex
In this case you are creating a std::String from a 'c' char array so the ctor of the std::string assumes that 'c' strings end at '0'. Since it's only passed an address in memory how else can it know where the string ends?
ps. If you want to store an array of bytes you should probably be using std::vector
Share Improve this answer Follow edited Dec 14, 2011 at 19:20 answered Dec 14, 2011 at 19:10 Martin BeckettMartin Beckett 96k28 gold badges195 silver badges268 bronze badges 1- he doesn't cout a char array, he couts a std::string object, which doesn't have this issue. – Mooing Duck Commented Dec 14, 2011 at 19:16
Try:
#include <iostream> #include <string> int main() { unsigned char cbuffer[]={0x61,0x62,0x00,0x63,0x0}; // Here s1 is treating the cBuffer as a C-String // Thus it will only read upto the first '\0' character std::string s1(reinterpret_cast<const char*>(cbuffer)); std::cout << s1 << "\n"; // Here s2 is treating the cBuffer as an array. // It reads the specified length into the string. std::string s2(reinterpret_cast<const char*>(cbuffer), sizeof(cbuffer)/sizeof(cbuffer[0])); // Note: How std::cout prints the '\0' character may leave it empty. std::cout << s2 << "\n"; } Share Improve this answer Follow answered Dec 14, 2011 at 19:20 Loki AstariLoki Astari 264k86 gold badges342 silver badges570 bronze badges Add a comment | 1The 0x00 byte is used as a sentinel to mark the end of the string in C. The entire array however remains in memory. You can use an alternate constructor for std::string if you want the string to contain the entire character array. But printing that string would still give you only "ab". This decision to represent C strings in this manner is one of those arbitrary decisions that we are stuck with.
Share Improve this answer Follow answered Dec 14, 2011 at 19:20 shibumishibumi 3782 silver badges11 bronze badges Add a comment | 00x00 is a non print character, 0..0x20, are all non print chars although some serve as line breaks. 0x00 serves to terminate a string.
Share Improve this answer Follow answered Dec 14, 2011 at 19:16 JohnJohn 6,6387 gold badges53 silver badges82 bronze badges Add a comment | 0What do you want to be substituted (and printed) for 0x00 in the resulting string?
The constructor is responsible for conversion of char[] into a string. As others pointed out, you must use different constructor. The code below is working for me, but it is not very roboust. The first parameter must be a pointer to the array (you are free to use safer casting) and the second parameter is the length of the array (you are free to calculate this in a more sophisticated way).
#include <iostream> int main() { unsigned char cbuffer[]={0x61,0x00,0x62,0x63,0x00}; std::string sbuffer((char *)cbuffer,5); std::cout << sbuffer << std::endl; } Share Improve this answer Follow edited Dec 15, 2011 at 8:00 answered Dec 14, 2011 at 19:34 meolicmeolic 1,1972 gold badges20 silver badges48 bronze badges Add a comment |Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Draft saved Draft discardedSign up or log in
Sign up using Google Sign up using Email and Password SubmitPost as a guest
Name EmailRequired, but never shown
Post Your Answer DiscardBy clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged
or ask your own question.- The Overflow Blog
- Your docs are your infrastructure
- Featured on Meta
- More network sites to see advertising test [updated with phase 2]
- We’re (finally!) going to the cloud!
- Call for testers for an early access release of a Stack Overflow extension...
Related
2 What happens when a char array is initialized to '\0'? 2 What does (char)0 mean in c++? 4 Character Array, \0 1 assigning 0x00 to an array in C? 1 Program picking '\0' even when it is not mentioned - Clarification 2 c++ empty char array has length > 0 1 storing 0 in a unsigned char array 2 Get away with Initialize the char array without putting \0 at the end of string 0 Different behavior of '\0' in Character Array and String 0 Char array to string and copy character \0Hot Network Questions
- Is BNF grammar in TeXbook correct?
- Where on Earth do tides go out furthest?
- What does GB Shaw mean when he says "like the butcher's wife in the old catch" here?
- Wouldn't the ban of TikTok violate freedom of speech?
- How do I go about rebranding a fully deleted project that used to have a GNU General Public License v3.0 but is now fully inaccessible
- Publishing corollaries of previously published results
- Identifying a TNG episode where Dr. Pulaski instructs another doctor on a sling
- Table structure with multiple foreign keys and values
- What would T-Rex cavalry be used for?
- Does length contraction "break the speed limit"?
- Solving Large size problems in industry: Tips and Tricks
- Can I find the inverse of a polynomial directly in its NTT form?
- Walks in Nice (Nizza)
- What is 擦边 as in the case of the athlete champion turned dancer?
- Angular orientation of exact solution of the Hydrogen Schrödinger Equation
- Are there any examples of exponential algorithms that use a polynomial-time algorithm for a special case as a subroutine (exponentially many times)?
- Find the Smallest Data Type for a Number
- Why did the angel strain or dislocate Yaakov's hip-socket?
- Special stairs of infinites and infinitesimals
- What do border officials do with my passport when I tell them that I'm entering as the spouse of an EU national?
- How important is storytelling when submitting a grant application (or even a science paper)?
- What is this Stardew Valley item?
- If "de-" means "down" or "off" and "sub-" means "under", what is the latin prefix- meaning "up"?
- Can you make 5 x 3 “magic” rectangles?
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
lang-cppTừ khóa » C++ 0x00
-
[Solved] How Do I Display 0x00? - CodeProject
-
How To Append To A String A Value 0x00 "00" And Not "\0" Char - MSDN
-
Binding An SSL Certificate To A Port In Windows C++ - Gists · GitHub
-
C++ UART MH Z19 CO2 Carbon Dioxid Sensor - GitHub Gist
-
Cad - Arm Compiler For Embedded Reference Guide
-
ARM Compiler Toolchain V4.1 For µVision Using The Fromelf Image ...
-
0x00 In C - C Board
-
Best Way To Point Array To A Method | Spiceworks Tech
-
Cannot Create C++ Project "Hexadecimal Value 0x00 Is An Invalid ...
-
Bit Level Operations
-
SPL Binary Encoding - IBM
-
ASCII Chart & ISO 1252 Latin-1 Char Set