2
Good evening, I’m having a problem, I’m wanting to copy information from a file to an array that allocates dynamically, the text file contains this:
....* *.... ..... .*... .....
(5 rows and 5 columns that will go to the matrix I’ve allotted using realloc because I don’t know the number of rows and columns that the information inside the file has).
I need to copy this to an array, but remembering that I don’t know the file size so I have to use feof. I have a problem with segmentation and I don’t know where, and I am doubtful if the passage of the file pointer and the process within the "reading" function is being done in a correct way.Below is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** leitura(char* nome)//Declaracao de funcao que aloca a matriz
{
FILE* ponteiro;
int i = 0,j = 1, k ,l;
char** campo = NULL;
char carac;
ponteiro = fopen("nome", "w");
while(!feof(ponteiro))
{
i++;
campo = (char**) realloc(campo, i * sizeof(char*));
while(fscanf(ponteiro, "%c", &carac) != '\n')
{
campo[j - 1] = (char*) realloc(campo[j - 1], j * sizeof(char));
campo[i - 1][j - 1] = carac;
j++;
}
}
for(k = 0; k < i; k++)
{
for(l = 0; l < j; l++)
{
printf("%c", campo[i][j]);
}
printf("\n");
}
fclose(ponteiro);
return campo; //Retorno da matriz alocada dinamicamente
}
int main (void)
{
int tamanho = 0, linha = 0, coluna = 0;
char* nome = NULL;
char** retornoCampo = NULL;
size_t tam = 0;
int i, j;
int opcao = 0;
scanf("%d", &opcao);
switch(opcao) //Opcoes a serem escolhidas
{
case 1: //Leitura
getline(&nome, &tam, stdin); //Funcao para adquirir o nome do arquivo
nome[strlen(nome) - 1] = '\0';
printf("%s\n", nome);
retornoCampo = leitura(nome);
break;
case 2: //Inicializacao do tabuleiro
break;
case 3: //Acao do usuario
break;
}
return 0;
}
Debugger a la carte
– Maniero