Skip to content

Instantly share code, notes, and snippets.

@gabrielbiga
Created August 4, 2014 14:10
Show Gist options
  • Save gabrielbiga/99bbf9b8ffe5954ddba1 to your computer and use it in GitHub Desktop.
Save gabrielbiga/99bbf9b8ffe5954ddba1 to your computer and use it in GitHub Desktop.
Matriz na memória
#include <stdio.h> //FUCKING I/O
#include <stdlib.h>
/* D:/matriz.txt ~>
* 6
* 101011
* 111100
* 101000
* 100111
* 011011
* 000111
*/
//Passe o nome do arquivo e um endereco para retorno de linhas
int** LerMatriz(char arq[], int *qtdeLinhas)
{
FILE *fr;
int chars = 0; //Caracteres pegos
int n; //Qtde de linhas
int lin = -1, col = 0; //Linha e coluna ** LINHA COMEÇA DE -1 POR CAUSA DA PRIMEIRA LINHA IGNORADA! **
int i;
//TAMBEM PODERIA SER ~~> char buff[1]; (USE O QUE FOR MAIS BONITO :))
char *buff = malloc(sizeof(char)); //Buffer
int **matriz; //Matriz
fr = fopen (arq, "rt");
while(fgets(buff, 2, fr) != NULL)
{
if (chars == 0) {
//Pegando qtde de linhas
sscanf(buff, "%d", &n);
//Lembrando que esperamos sempre matriz N por N
//Alocando matriz na memoria
matriz = (int**) malloc(n * sizeof(int*));
//Alocando as linhas
for(i = 0; i < n; i++)
matriz[i] = (int*) malloc(n * sizeof(int));
//EU FARIA ASSIM MAS, EM VEZ DISSO, VOCE PODE USAR ELSE. (VEJA O QUE TEM MAIS DESEMPENHO PRA VOCE)
chars++;
continue;
//---
} // else {
if (buff[0] != '\n') {
sscanf(buff, "%d", &matriz[lin][col]);
col++;
} else {
//Quebra de linha!
lin++;
col = 0;
}
// }
chars++;
}
fclose(fr);
//Retorna qtde de linhas
*qtdeLinhas = n;
//Retorna matriz...
return matriz;
}
int main() {
int i, j; //Navegacao
int n; //QTDE DE LINHAS LIDAS
int **matriz = LerMatriz("D:/matriz.txt", &n);
//Mostrando...
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d", matriz[i][j]);
}
printf("\n");
}
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment