Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

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;
0
anshuma
Asked:
anshuma
  • 4
  • 2
1 Solution
 
Jaime OlivaresSoftware ArchitectCommented:
It works well, just need an ending null character after the last line:

*q = 0;
cout << s << endl;
0
 
Jaime OlivaresSoftware ArchitectCommented:
Sorry, I mean "need an ending null character **before** the last line"

string size is determined by the position of the null character.
0
 
anshumaEngineeringAuthor Commented:
i don't get it
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Jaime OlivaresSoftware ArchitectCommented:
>i don't get it
That means you haven't understood the problem?
I your code working well now?
0
 
anshumaEngineeringAuthor Commented:
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".
0
 
Jaime OlivaresSoftware ArchitectCommented:
>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.

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now