user1927638
user1927638

Reputation: 1173

Allocating C array based on size of another array

I have written a method in C that removes characters from a string

char* removeChars(char input[], char remove[]) 
{
    int src, dst = 0;
    int size = strlen(input);
    bool flags[128];

    char output[18]; // <- This should be output[size]!

    int i;
    for(i=0; i<128; i++) {
        flags[i] = false;
    }

    int j=0;
    while(remove[j] != '\0') {
        flags[remove[j]] = true;
        j++;
    }

    for(src=0; src<size; src++) {
        if(flags[input[src]] != true) {
            output[dst++] = input[src];
        }
    }
    return output;
}

One of the issues that I am having is that when I attempt to set the size of the output array using size (i.e. char output[size]), The output array appears to always have zero elements. It only seems to work when I specify a specific size (like 18). Should I be using strcpy or malloc instead? If so, how should it be done?

Upvotes: 0

Views: 872

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

Your program has undefined behaviour because you are returning pointer to the first element of a local array that in general case will be destroyed after exiting the function.

So you have to allocate the array in the heap dynamically.

The other problem is that you do not append the output string with the terminating zero.

The function woild look simpler if you would remove characters in the source string that is "in place". In this case there is no any need in an additional array.

Also you could use standard function strchr declared in header <string.h> that to determine whether a given character in the source string is present in the string that contains characters to be removed.

Upvotes: 1

Gopi
Gopi

Reputation: 19864

char *output = malloc(sizeof(char) * (size+1));

If you want memory to be dynamically allocated using size. Once you are done using this memory please free it.

free(output);

Upvotes: 2

Related Questions