Skip to content

Instantly share code, notes, and snippets.

@kaneshin
Created November 22, 2011 09:16
Show Gist options
  • Save kaneshin/1385271 to your computer and use it in GitHub Desktop.
Save kaneshin/1385271 to your computer and use it in GitHub Desktop.
dynamic definition of vector and matrix.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void
print_vec(double *v, int n) {
int i;
for (i = 0; i < n; i++) {
printf("vec_%d = %.4f\n", i + 1, v[i]);
}
}
void
init_vec(double *v, int n) {
int n5 = n % 5;
int i;
for (i = 0; i < n5; i++) {
v[i] = 1.5;
}
for (; i < n; i+=5) {
v[i] = 1.;
v[i + 1] = 1.;
v[i + 2] = 10.;
v[i + 3] = 1.;
v[i + 4] = 1.;
}
}
void
print_mat(double **a, int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%6.2f", a[i][j]);
}
printf("\n");
}
}
void
init_mat(double **a, int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a[i][j] = i + j;
}
}
// a[2][3] = -1.;
}
int
main(int argc, char* argv[]) {
int n = 39;
double *x = (double *)malloc(n * sizeof(double));
double **a;
int i;
// mallocした最初の要素にすべての領域を確保
a = malloc(n * sizeof(double *));
a[0] = malloc(n * n * sizeof(double));
for (i = 1; i < n; i++) {
a[i] = a[0] + n * i;
}
init_vec(x, n);
init_mat(a, n, n);
print_vec(x, n);
printf("---\n");
print_mat(a, n, n);
// mallocを解放する
free(a);
free(x);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment