To split in .c
and .h
it would be enough to create a function in .h
, and in .c
put all the code it has. Then it would only be necessary to call main
. This would not be a great idea but it would look like this:
array.h
#include <stdio.h>
#ifndef MATRIZ_H_INCLUDED
#define MATRIZ_H_INCLUDED
void programa_matriz();
#endif // MATRIZ_H_INCLUDED
array.c
#include "matriz.h"
void programa_matriz(){
//todo o código que tinha no main aqui
}
main.c
#include "matriz.c"
int main(){
programa_matriz();
return 0;
}
Split functions by functionality
One of the ideas of separating in .h
and .c
is to be able to include .h
and use the functions you need for each separate feature. This means that it will hardly make sense to "turn a program into a function" but rather to turn each functionality into a function, thus giving as much code reuse and organization as possible.
In your case you could at least separate in two functions:
Letting the arrays be created in main
same.
Example:
array.h
#include <stdio.h>
#ifndef MATRIZ_H_INCLUDED
#define MATRIZ_H_INCLUDED
void inverter_matriz(int matriz[2][2], int matriz_invertida[2][2]);
void mostrar_matriz(int matriz[2][2]);
#endif // MATRIZ_H_INCLUDED
array.c
#include "matriz.h"
void inverter_matriz(int matriz[2][2], int matriz_invertida[2][2]){
int i, j;
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
matriz_invertida[j][i] = matriz[i][j];
}
}
}
void mostrar_matriz(int matriz[2][2]){
int i, j;
for(i = 0; i < 2; i++) {
printf("[ ");
for(j = 0; j < 2; j++) {
printf("%d ", matriz[i][j]);
}
printf("]\n");
}
}
main.c
#include <stdio.h>
#include "matriz.h"
int main(int argc, char *argv[]) {
int matriz_1[2][2];
int matriz_2[2][2];
matriz_1[0][0] = 1;
matriz_1[0][1] = 2;
matriz_1[1][0] = 3;
matriz_1[1][1] = 4;
inverter_matriz(matriz_1, matriz_2);
mostrar_matriz(matriz_2);
return 0;
}