Sa se realizeze un program in limbajul C ce extrage elementele cuprinse in intervalul [5,10] dintr-o matrice si le stocheaza intr-un vector. Programul se va realiza folosind functii si pointeri (matrice = pointer dublu - int **m, vector = pointer simplu - int *v).
Răspunsuri la întrebare
Răspuns:
#include <stdio.h>
#include <stdlib.h>
void extract_elements(int** matrix, int* vector, int rows, int columns, int* k) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (matrix[i][j] >= 5 && matrix[i][j] <= 10) {
vector[(*k)++] = matrix[i][j];
}
}
}
}
int main() {
int rows = 3;
int columns = 4;
int **matrix = (int**)malloc(rows*sizeof(int*));
for(int i =0;i<rows;i++)
matrix[i] = (int*)malloc(columns*sizeof(int));
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;
matrix[1][0] = 5;
matrix[1][1] = 6;
matrix[1][2] = 7;
matrix[1][3] = 8;
matrix[2][0] = 9;
matrix[2][1] = 10;
matrix[2][2] = 11;
matrix[2][3] = 12;
int k = 0;
int* vector = (int*)malloc(8*sizeof(int));
extract_elements(matrix, vector, rows, columns, &k);
printf("Elemente din intervalul [5,10]: ");
for (int i = 0; i < k; i++) {
printf("%d ", vector[i]);
}
printf("\n");
for(int i =0;i<rows;i++)
free(matrix[i]);
free(matrix);
free(vector);
return 0;
}
Explicație: