Question has been asking before, but I am still a bit at a loss as to the best way. I have an integer and would like to obtain a char* to use as a member of a struct.
Similar questions are for example
here or here.
I’d rather not use stringstream or lexical_cast. Which as far as I can see basically leaves itoa, sprintf and snprintf.
I guess part of my problem is that I don’t quite know how char pointers work.
- If I request a
char str[12], that reserves 12 characters? - I presume that memory has then been assigned?
- So how does null termination work?
- Is that at the end of the 12 characters (with spaces padding?), or
if the number only uses 2 characters, would it happen after two? - Does the buffer size matter or should I just go with some maximum
(30 or so I believe for 32 bits)? - And if I use the pointer later in a simple struct, will the memory
be cleared automatically or do I need a destructor? - Does the destructor need to know the initialize buffer size?
- Why does no one bother to calculate the buffer length from the
actual number? - Is snprintf recommended over itoa?
Thanks
Yes, this reserves 12 characters (bytes) on the stack.
strnow points to the beginning of 12 bytes of contiguous memory that has been allocated on the stack.In this case you have to null-terminate the string yourself (it doesn’t automatically happen with this type of declaration).
So if you wanted to make
strhold some (null-terminated) string value, you would do the following:Another way to get a null-terminated string is to do the following:
There is no automatic padding with spaces.
If the pointer is pointing to a piece of memory allocated on the stack, then the memory will be recovered when the stack is popped. Otherwise, if you allocate memory on the heap such as:
Then you will have to de-allocate the memory using
deleteorfree(depending on which method you used).In this context we’re talking about heap-allocated memory and therefore the answer is no. The system knows how much memory was allocated. That’s why you just give the pointer to
deleteandfreewithout having to provide a size.You can if you know that your number will never exceed a certain amount (say, 4 digits), but it’s usually easier to just give the maximum possible length, because in the end you’ll only be wasting a few bytes per string, which isn’t a big deal unless you have some really tight memory constraints.
I would say yes because
snprintfis considered “safe” because it respects the buffer size that you give it, whereasitoawill happily fill your buffer without checking its size (possibly running past the allocated space and overwriting other memory).Both
snprintfanditoawill null-terminate the strings for you.