Amit
asked on
changing the size of a string
The following code tries to remove the character 's' from the string. But the code doesn't work, i know its becoz of the if condition. Please help me in creating function that actually modifies the original string.
__________________________ __________ __________ __________ __________ _______
char s[] ="hissalpha";
cout << s << endl;
char *p=s;
char *q=s;
while (*p)
{
if (*p !='s')
{
cout << *p << endl;
*q=*p;
q++;
}
p++;
}
cout << s << endl;
__________________________
char s[] ="hissalpha";
cout << s << endl;
char *p=s;
char *q=s;
while (*p)
{
if (*p !='s')
{
cout << *p << endl;
*q=*p;
q++;
}
p++;
}
cout << s << endl;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
i don't get it
>i don't get it
That means you haven't understood the problem?
I your code working well now?
That means you haven't understood the problem?
I your code working well now?
ASKER
tell me one thing, what happens to the memory that was allocated for the bigger string. Like if it was size 10 in the beginning and then on removal of 3 chars it becomes size 7. I am sure we don't need delete because we are not using "new".
>I am sure we don't need delete because we are not using "new"
That's correct.
>what happens to the memory that was allocated for the bigger string
As a general rule, every chunk of allocated memory in C/C++ (by using new or not) is deallocated entirely, so if you put an ending null character this will not alter the fact that 10 bytes will be deallocated, not 7. That's because deallocating routine doesn't inspect if a null character is present in buffer.
That's correct.
>what happens to the memory that was allocated for the bigger string
As a general rule, every chunk of allocated memory in C/C++ (by using new or not) is deallocated entirely, so if you put an ending null character this will not alter the fact that 10 bytes will be deallocated, not 7. That's because deallocating routine doesn't inspect if a null character is present in buffer.
*q = 0;
cout << s << endl;