MintyAnt
MintyAnt

Reputation: 3058

Remove first index in a char*[]

In C I want a function like this:

bool RemoveFirstIndex(char* inArray[])

which goes in and takes out the very first element in that array.

e.g.

inArray = "Hello\o", "How\o", "Are\o"
RemoveFirstIndex(inArray)
inArray = "How\o", "Are\o"

Not sure how to go about it.

I get the idea that I would have to create a new array of inSize - 1, and just fill it with everything except index 0. But if I do that, does the function need to return a new char*[]? Isnt that a bit wasteful?

Thank you.

Upvotes: 2

Views: 1721

Answers (3)

bames53
bames53

Reputation: 88155

void RemoveFirstIndex(std::vector<std::string> &inArray) {
    if (!inArray.empty())
        inArray.erase(inArray.begin());
}

std::vector<std::string> array = {"Hello", "How", "Are"};
RemoveFirstIndex(inArray)
// array now contains {"How", "Are"}

You shouldn't want to use an array of char pointers, but if you do you need to indicate its size and a way for the function to indicate the new size afterward.

size_t RemoveFirstIndex(char **inArray, size_t n) {
    if (n==0)
       return n;

    std::rotate(inArray,inArray+1,inArray+n);
    // raw pointers indicate we don't own these resources
    //   so we don't need to deallocate anything...
    return n-1;
}

char *array[] = {"Hello", "How", "Are"};
size_t size = sizeof array/sizeof *array;
for (size_t i=0;i<size;++i)
    std::cout << array[i] << '\n';

size = RemoveFirstIndex(array,size);
for (size_t i=0;i<size;++i)
    std::cout << array[i] << '\n';

Upvotes: 0

Nicolas Bachschmidt
Nicolas Bachschmidt

Reputation: 6505

Why remove the first element or create a new array?

Just can just increment your pointer so it points to the next item in the array.

char **newArray = inArray + 1;

newArray is valid as long as inArray is.

Upvotes: 11

user529758
user529758

Reputation:

Use dynamic memory management and just shrink that array:

// create the array
size_t arrsize = 10;
char **arr = malloc(arrsize * sizeof(*arr));
int i;
for (i = 0; i < arrsize; i++)
    arr[i] = malloc(/* whatever the length of the string (incl. NUL) is */);

// then use it like this:
RemoveFirstIndex(arr, &arrsize);

bool RemoveFirstIndex(char **inArray, size_t *arr_len)
{
    if (*arr_len == 0 || inArray == NULL)
        return false;

    free(inArray[0]);
    int i;
    *arr_len--;
    for (i = 0; i < *arr_len; i++)
        inArray[i] = inArray[i + 1];

    inArray = realloc(inArray, sizeof(*inArray) * (*arr_len));

    return true;
}

Upvotes: 0

Related Questions