Reputation: 112
I have such function:
bool filtruj(char* text, bool(*f)(char)) {
while(*(text)!='\0')
{
bool sprawdzWartosc = f(*(text));
if(sprawdzWartosc)
{
printf("run");
b=*(text);
while(b!='\0')
{
printf("run2");
*(text) = *(text+1);
text++;
}
}
}
return false;
}
which when the sprawdzWartosc is true, delete this char and move other characters one to the left.
The question is: how to back to the position of pointer which is used in var sprawdzWartosc? Becuase when I'm moving characters my pointer is at the end of *(text).
I can't use int, short, long variables, only pointers.
Upvotes: 1
Views: 71
Reputation: 393567
b=*text;
while(b!='\0')
// ...
This just keeps comparing the same character b
, and it will never be \0
.
Perhaps you wanted to use another pointer?
Here's what I think you were trying to achieve: Live on Coliru
bool filter(char* text, bool(*pred)(char)) {
char* out = text;
while (*text)
{
if (pred(*text))
{
++text; // just skip
} else
{
*out++ = *text++; // copy out
}
}
*out = '\0';
return (out != text); // true if characters were filtered
}
#include <cctype>
#include <cstring>
#include <cstdio>
bool foo(char c)
{
return isalpha((int)(unsigned char)c);
}
void test(const char* input)
{
char* s = strdup(input);
printf("%s -> ", s);
bool b = filter(s, foo);
printf("%s (%s)\n", s, b?"true":"false");
}
int main()
{
test("12346 234890-98 .");
test("12a46 awesome-98!");
}
Printing
12346 234890-98 . -> 12346 234890-98 . (false)
12a46 awesome-98! -> 1246 -98! (true)
Upvotes: 1
Reputation: 24269
I think what you are trying to do is iterate over the body of a string and delete characters for which a call to f
returns true.
bool filtruj(char* text, bool(*f)(char)) {
while(*(text)!='\0') {
bool sprawdzWartosc = f(*(text));
if(sprawdzWartosc) {
for (char* cur = text; *cur; ++cur) {
*cur = *(cur+1);
}
}
}
return false;
}
Note that your original code did this
b = *(text);
while (b != '\0')
The assignment, b = *(text)
copies the current value at the address text currently points to into the variable b - it does not make b
magically track the current value of text.
int i = 5;
int* ptr = &i;
int j = *ptr;
++i;
printf("j = %d\n", j);
prints 5, not 6.
Upvotes: 0