2014-05-18 2 views
0

안녕하세요, 저는 텍스트 파일을 기반으로 배열을 동적으로 초기화하려고하지만, 어떤 이유로 그것을 잘못하고 있습니다. "malloc"라인에서 "texto"가 초기화되지 않았다는 오류가 발생합니다. 이 포인터를 반환하기 때문에동적 배열 C를 초기화하십시오.

char nome[] = "partidas.txt"; 
f = fopen(nome, "rt"); 
int size = fsize(f); 

char **texto; 
**texto = (char)malloc(size); 

int i = 0; 
while ((fgets(texto[i], sizeof(texto), f) != NULL)) 
{ 
    printf("%s\n", texto[i++]); 
} 
+4

당신은 캐릭터에 malloc에 ​​캐스팅 수 없습니다. 어쨌든 왜 문자 포인터가 문자 포인터 (char **)에 대한 포인터가되기를 원하십니까? 당신이 그 줄'texto = malloc (size);을 만들 필요가 있다고 가정하면 방금 작성한 배열의 모든 포인터를 malloc하는 루프가 필요합니다. –

+1

파일에서 문자열 배열을 읽으려고합니까? –

+1

@JerryJeremiah 내가 사용하는 ** texto 원인은 동적 숯 texto [] [], 기본적으로 그냥 텍스트에 txt 파일의 크기를 넣고 다음 데이터로 채울 필요합니다. –

답변

0
//remember to include the right header files 

#include <stdio.h> 
#include <string.h> 
#include <errno.h> 

#define READ_LENGTH 1024 

char*  pFileContents = NULL; 
int  iContentsIndex = 0; 

long int sz = 0; 
FILE*  pFD = NULL; 
int  readCount = 0; 
int  stat = 0; 

// note: all errors are printed on stderr, success is printed on stdout 
// to find the size of the file: 
// You need to seek to the end of the file and then ask for the position: 

pFD = fopen("filename", "rt"); 
if(NULL == pFD) 
{ 
    perror("\nfopen file for read: %s", strerror(errno)); 
    exit(1); 
} 

stat = fseek(pFD, 0L, SEEK_END); 
if(0 != stat) 
{ 
    perror("\nfseek to end of file: %s", strerror(errno)); 
    exit(2); 
} 

sz = ftell(pFD); 

// You can then seek back to the beginning 
// in preparation for reading the file contents: 

stat = fseek(pFD, 0L, SEEK_SET); 
if(0 != stat) 
{ 
    perror("\nfseek to start of file: %s", strerror(errno)); 
    exit(2); 
} 

// Now that we have the size of the file we can allocate the needed memory 
// this is a potential problem as there is only so much heap memory 
// and a file can be most any size: 

pFileContents = malloc(sz); 
if(NULL == pFileContents) 
{ 
    // handle this error and exit 
    perror("\nmalloc failed: %s", strerror(errno)); 
    exit(3); 
} 


// then you can perform the read loop 
// note, the following reads directly into the malloc'd area 

while(READ_LENGTH == 
     (readCount = fread(pFileContents[iContentsIndex], READ_LENGTH, 1, pFD)) 
    ) 
{ 
    iContentsIndex += readCount; 
    readCount = 0; 
} 

if((iContentsIndex+readCount) != sz) 
{ 
    perror("\nfread: end of file or read error", strerror(errno)); 
    free(pFileContents); 
    exit(4); 
} 

printf("\nfile read successful\n"); 

free(pFileContents); 

return(0); 
+0

안녕하세요 @ user3629249,이 코드에 몇 가지 오류가 있습니다. "함수 호출에서 인수가 너무 많습니다."strerror (errno)
"유형"char * "값은"char * "유형의 엔터티에 할당 할 수 없습니다."pFileContents = malloc (sz); –