Doe
Doe

Reputation: 23

C - quicker way to shift an array without using int

as my assignment I'm writing a programm that's supposed to check char array with bool function and delete all chars in array that return true. The thing is that I'm not allowed to use indexing (nor any kind of int and libraries). I wrote a code that shifts my array but it is too slow. I would be very grateful if anyone could point me to quicker way to do it.

bool filter(char* array, bool(*function)(char))
{
    if(array)
    {
        char *start = array;
        while(*(array) != 0)
        {
            if(function(*array) == false)
            {
                start++;
                array++;
            }
            else
            {
                while(*(array) != 0)
                {
                    *(array) = *(array + 1);
                    array++;
                }
                *(array) = 0;
                tablica = start;
            }
        }
    }
}

I'm looking forward to your reply.

Upvotes: 1

Views: 120

Answers (3)

wildplasser
wildplasser

Reputation: 44250

K&R style:

void filter(char *array, bool(*function)(char))
{
    char *dst;
    if(!array) return;

    for (dst=array; *dst = *array++; ) {
        if (function(*dst)) continue;
        dst++;
    }
}

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114548

You do not need to reshift the entire array every time a character is removed. Just keep a record of the current to and from positions when you are doing your copying. As long as there is no possibility of adding elements back into the array, you will not overwrite anything:

bool filter(char* array, bool(*function)(char)){
    if(array){
        char *start = array;
        while(*(array) != 0){
            if(function(*array) == false){
                *start = *array;
                start++;
            }
            array++
        }
        *start = '\0';
    }
    return true;
}

Upvotes: 2

Robᵩ
Robᵩ

Reputation: 168876

Your professor is pushing you toward using pointers instead of indexes. Try this:

//UNTESTED
void filter(char* array, bool(*function)(char)) {
  char *src;
  char *dest;
  char c;

  src = dest = array;

  while(c = *src++) {
    if (!function(c))
      *dest++ = c;
  }
  *dest = 0;
}

Upvotes: 2

Related Questions