Skip to content

Instantly share code, notes, and snippets.

@jmbr
Created November 17, 2010 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbr/703105 to your computer and use it in GitHub Desktop.
Save jmbr/703105 to your computer and use it in GitHub Desktop.
Use of stack allocated vectors with the GNU Scientific Library.
/*
Compile with:
gcc -Wall -std=c99 test_stack_allocation_of_vectors.c -o test_stack_allocation_of_vectors `gsl-config --libs`
*/
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <assert.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#define block_init(size_, data_) { .size = size_, .data = data_ }
#define vector_from_block_init(block, offset, n, stride_) \
{ .data = block.data + offset, \
.size = n, .stride = stride_, .owner = 0 }
static void test_stack_allocation_of_vectors(const size_t N)
{
assert(N >= 4);
double buf[N];
gsl_block b = block_init(N, buf);
gsl_vector u = vector_from_block_init(b, 0, 2, 1);
gsl_vector v = vector_from_block_init(b, 2, 2, 1);
gsl_vector_set_basis(&u, 0);
gsl_vector_set_basis(&v, 1);
gsl_vector_fprintf(stdout, &u, "%g");
gsl_vector_fprintf(stdout, &v, "%g");
double res[3];
gsl_blas_ddot(&u, &u, &res[0]);
gsl_blas_ddot(&u, &v, &res[1]);
gsl_blas_ddot(&v, &v, &res[2]);
printf("<u, u> = %g, <u, v> = %g, <v, v> = %g\n", res[0], res[1], res[2]);
}
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Usage: %s NUMBER\n", argv[0]);
exit(EXIT_FAILURE);
}
test_stack_allocation_of_vectors((size_t) atoi(argv[1]));
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment