malloc instead of array syntax

Table of Contents

#define N 10000000

void vector_add(float *out, float *a, float *b, int n) {
    for(int i = 0; i < n; i++){
        out[i] = a[i] + b[i];
    }
}

int main(){
    float *a, *b, *out;

    // Allocate memory
    a   = (float*)malloc(sizeof(float) * N);
    b   = (float*)malloc(sizeof(float) * N);
    out = (float*)malloc(sizeof(float) * N);

    // Initialize array
    for(int i = 0; i < N; i++){
        a[i] = 1.0f; b[i] = 2.0f;
    }

    // Main function
    vector_add(out, a, b, N);
}

I prefer array being initialized this way, as memory is explicitly allocated with functions, instead of wonky syntax.

The above code could trivially be rewritten in lisp.

1. link

this snippet is taken from CUDA official tutorial01

Backlinks

Author: Linfeng He

Created: 2024-04-03 Wed 20:21