cours_progra/bac2/os/chap2/ex3.c
Debucquoy b0f02b0d5d
.
2023-10-18 20:27:40 +02:00

63 lines
1.2 KiB
C

#include <stdlib.h>
#include <stdio.h>
#define print_vec(vec) for (int i = 0; i < (vec)->size; ++i) { printf("%d, ", (vec)->data[i]); } printf("\n")
struct vec {
int size;
int *data;
};
struct vec* new(unsigned int n);
struct vec* add(const struct vec *v, const struct vec *w);
struct vec* smul(double s, const struct vec *v);
int main(void)
{
struct vec *v = new(4);
v->data[0] = 1;
v->data[1] = 2;
v->data[2] = 3;
v->data[3] = 4;
print_vec(v);
struct vec *w = new(4);
w->data[0] = 5;
w->data[1] = 6;
w->data[2] = 7;
w->data[3] = 8;
print_vec(w);
struct vec *added = add(v, w);
print_vec(added);
struct vec *multiplied = smul(3, v);
print_vec(multiplied);
}
struct vec* new(unsigned int n){
struct vec* ret = malloc(sizeof(struct vec));
ret->size = n;
ret->data = malloc(sizeof(int) * n);
return ret;
}
struct vec* add(const struct vec *v, const struct vec *w){
if(v->size != w->size)
return NULL;
struct vec *ret = new(v->size);
for (int i = 0; i < v->size; ++i) {
ret->data[i] = v->data[i] + w->data[i];
}
return ret;
}
struct vec* smul(double s, const struct vec *v){
struct vec *ret = new(v->size);
for (int i = 0; i < v->size; ++i) {
ret->data[i] = v->data[i] * s;
}
return ret;
}