Reputation: 19
There is pointer to string let say: char *p = "abcdef" I want to delete some of the chars.
Let say every second char, so i want to get *p="ace" my algorithm is something like:
int i=1,j=1
for(;p != '\0';p++,i++)
if (i % 2 ==0)
*(p - j++)= *p
*(p-j)='\0'
This algorithm is find the every second char of course but not matter how I try to write the "delete" process or there are compilation errors or the string is unchanged.
I start to believe there is no way to solve that issue without any malloc help. Again i need to do it on O(n) without any other STRINGS arrays.
Upvotes: 1
Views: 95
Reputation: 386676
p != '\0'
should be *p != '\0'
(or *p != 0
or *p
).i
should be initialized to 0
. (You are keeping the wrong ones.) j
should be initialized to 0
. (Off by one error.)j
needs to be incremented each time p
is incremented.Your code would be more readable and less fragile if you avoided offsets relative to an unrelated pointer.
void filter_inplace(char* src) {
char* dst = src;
for (size_t i=0; src[i]; ++i) {
if (i % 2 == 0)
*(dst++) = src[i];
}
*dst = 0;
}
Alternative:
void filter_inplace(char* src) {
char* dst = src;
while (1) {
if (!*src) break;
*(dst++) = *(src++);
if (!*src) break;
src++;
}
*dst = 0;
}
Of course, you can't do the following because p
points to read-only memory:
char* p = "abcdef"; # XXX Should be "const char*".
filter_inplace(p); # XXX Overwrites read-only memory.
You could do the following:
char p[] = "abcdef";
filter_inplace(p);
You could do the following:
char* p = strdup("abcdef");
filter_inplace(p);
free(p);
Upvotes: 3
Reputation: 44340
I start to believe there is no way to solve that issue without any malloc help. Again i need to do it on O(n) without any other STRINGS arrays.
Kind of true. At least it is true that it can't be done without another string. Even if you used malloc
(or strdup
) for getting memory I would still consider it another string.
So as long a you initialize the char pointer like:
char *p = "abcdef";
it can not be done. You can't change any character in the string "abcdef"
.
If the above code was changed to
char p[] = "abcdef";
you would be able to do what you a trying. But even this could be considered as using another string as you have both the initializer string and char array.
Upvotes: 1