I have a working code for a function which takes a character and a number and forms a string by duplicating that character that number of times. Here is a piece that works perfectly fine.
char * buildstr(char c, int n)
{
char * pc = new char[n+1];
for (int i = 0; i < n; ++i)
{
*(pc+i) = c;
}
*(pc+n) = '\0';
return pc;
}
But if I use another logic where I directly increment the pointer itself directly then I get an error when I free up the memory in the main function using delete [].
What could be my problem ?
Thanks,
char * buildstr(char c, int n)
{
char * pc = new char[n+1];
for (int i = 0; i < n; ++i)
{
*pc = c;
pc++;
}
*(pc) = '\0';
return pc;
}
*(pc+i)you should use the equivalent and more readablepc[i].std::stringhas a constructor (see (2)) that does exactly this (and another big plus: it managed the memory for you).freeexpects as argument the starting address of a memory block that has been allocated using functionmalloc/calloc/realloc. Operatordeleteexpects as operand the starting address of a memory block that has been allocated using operatornew. You cannot just pass any address within that block of memory. I was about to ask you in a comment if you were serious about not being able to see the problem in your code, but then I realized your perception of a memory block as being some soft of "atomic unit".