An Interest In:
Web News this Week
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
Is there a way to convert dynamically allocated memory to static memory OR copy ptr contents in C/C?
For reference, static memory is memory that is memory that is assigned, managed, and freed for you (an example is
char const* str = "Hello World!";
).
C/C++ will clean that string up for you.
Dynamically allocated memory is memory you request, manage, and must clean yourself (an example isType_t* array = malloc( sizeof(Type_t)*arrLength );
).
I'm messing around with C strings in C++, even testing ideas for my own String
type. - And I was creating a String +(char c)
method, when I thought of something: "How can I return a String
object whose str
property is statically allocated, and not dynamically allocated?".
Since the only method of adding a character to an immutable string I can think of involves using malloc( (oldStrLen+1)*sizeof(char) )
, which is dynamically allocated.
So, is there a way I can copy the contents of a pointer to a new statically allocated pointer, or convert dynamically allocated memory to statically allocated memory in C/C++?
Thanks!
Cheers!
Original Link: https://dev.to/baenencalin/is-there-a-way-to-convert-dynamically-allocated-memory-to-static-memory-or-copy-ptr-contents-in-cc-127d
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To