[英]Initialize dynamic array c
Hello i want to dynamically initialize an array based on a text file, but for some reason im doing it wrong. 您好,我想基于文本文件动态初始化数组,但是由于某种原因,即时通讯做错了。 i get an error at line "malloc" that the "texto" is not being initialized. 我在“ malloc”行收到一个错误,提示“ texto”未初始化。
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++]);
}
//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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.