Cyber Gh
Cyber Gh

Reputation: 300

How to create a generic function to replace elements in an array?

I am trying to create a generic function in c to replace all occurences of an element in an array with another element, but I got stuck on implementing the generic function for replacing a string. It only works locally and doesn't affect the initial array.

I've tried making the arr_el parameter a double pointer but it keeps throwing seg fault.

How should I change the replaceString function in order for it to work?

void replaceString(void *arr_el, void* val) {
    char* arr_el_adr = *(char**)((arr_el));
    char *copy_val = malloc(strlen((char*)val) + 1);

    strcpy(copy_val, (char*)val);
    arr_el = &copy_val;
    printf("%s %s\n", *(char**)arr_el, arr_el_adr);
}

int equalString(void* a, void* b) {
    char* str1 = (char*)a;
    char* str2 = *(char **)b;

    return strcmp(str1, str2);

}

void replaceAll(void* el, void* replace_val, void *arr, int size, int dim, int(*equal)(void*, void*), void(*replace)(void*, void*)) {
    char *handler = arr;
    int i;

    for (i = 0; i < size; i++) {
        if (equal(el, arr + i*dim) == 0) {
            char *temp_handler = arr + i*dim;
            replace(temp_handler, replace_val);
        }
    }
}

int main() {
    char* arr[] = { "ana", "maria", "ana", "nothing" };

    int N = sizeof(arr) / sizeof(arr[0]);

    char x[] = "ana";
    char y[] = "gabriel";

    int i;

    replaceAll(x, y, arr, N, sizeof(char*), equalString, replaceString);

    for (i = 0; i < N; i++)
        printf("%s ", arr[i]);

    return 0;
}

On this test it should replace "ana" with "gabriel" on position 0 and 2.

Upvotes: 0

Views: 328

Answers (1)

bruno
bruno

Reputation: 32596

It only works locally and doesn't affect the initial array.

arr_el = &copy_val;

must be

*((char**)arr_el) = copy_val;

and in fact you function is complicated for nothing, can be

void replaceString(void *arr_el, void* val) {
    *((char**)arr_el) = strdup(val);
}

Out of that why do you use all that void* rather than the right type ? You say you want generic code, but the compiler complains because you do pointer arithmetic with void * in arr + i*dim whose can give a wrong result

Upvotes: 1

Related Questions