Hello i need allocate memory block in my string and then free memory but I don't know how use it correctly.
1 2 3 4 5 6 7 8
string retez1, retez2;
unsignedint velikost = 0;
char * vysledek;
if (retez1.size() > retez2.size())
velikost = retez1.size();
else velikost = retez2.size();
vysledek = (char*)malloc(velikost+1);
How can i allocate memory for string retez1,retez2 and vysledek ?
It should be size of string I enter as input(retez1,retez2) and (vysledek) represent result of retez1+retez2.
retez1 and retez2 can be long aroud 16000 sings. So what im doing wrong ?
How can i allocate memory for string retez1,retez2 and vysledek ?
you don't need to allocate memory to retez1 and retez2 since they are std::strings, memory is automatically managed by the string class.
vysledek on the other hand is a pointer to char which should be dynamically allocated to store a string.
So what im doing wrong ?
instead of doing all those memory allocations, you can just declare vysledek as string also, then copy value of retez1, and 2 using operator+ to the newly created one.
JockX can you post whole code ? If i use this i have typical problem with output and result is empy.
shadow fiend i can't use this because str1 and str2 is binary number (100101 1001010) and i need make sum of this and this is result. If i use this program crash.
There is a problem with the order in which events are happening. It doesn't make sense to set the size of vysledek at line 23 unsignedint velikost = retez1.size() + retez2.size () +1;
... because the user will enter the input strings afterwards, at line 40.
Instead, insert at line 86:
string vysledek(retez1.size(), '0');
If you really wanted to use a character array instead of a std::string, then you could do this - but it's more complicated:
char * vysledek = newchar[ retez1.size() + 2];
It needs to be 2 bytes longer than the longest input string (a) to allow for null terminator and (b) to allow for possible carry from adding the final pair of digits.
thank you, once again :) last thing i must check is if i have inputs like 00000001 and 000000001.
my output is 000000010 but i should get only "10" or when i get 00000000 000000 i should get output "0" and not 0000000000