'Write a function that allocates an array of 100 chars in the heap in C

Write a function that allocates an array of 100 chars in the heap, sets them to ’b’ if their index is divisible by 9 and to ’1’ otherwise, and deallocates the heap array.

How do I do this?



Solution 1:[1]

This should do it, but I couldn't test it.

void test() {
    char* arr = (char*)malloc(100*sizeof(char));
    for(int i = 0; i < 100; i++) {
        if(i % 9 == 0) {
            arr[i] = 'b';
        } else {
            arr[i] = '1';
        }
    }
    free(arr);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kenny