I am having a hard time dealing with malloc in C especially when allocating for array of struct. I have a program that basically store all the filenames and filesize in an array of struct. I got my program working without using malloc but I dont really like this way of programming. Could I get any help using malloc, in my program?
int getNumberOfFiles(char *path)
{
int totalfiles = 0;
DIR *d;
struct dirent *dir;
struct stat cstat;
d = opendir(path);
while(( dir = readdir(d)) != NULL) {
totalfiles++;
}
return totalfiles;
}
int main()
{
int totalfiles = getNumberOfFiles(".");
int i =0;
DIR *d;
struct dirent *dir;
d = opendir(".");
struct fileStruct fileobjarray[totalfiles];
struct stat mystat;
while(( dir = readdir(d)) != NULL) {
fileobjarray[i].filesize=mystat.st_size;
strcpy (fileobjarray[i].filename ,dir->d_name );
i++;
}
}
As you can see, I made a function called getnumberoffiles() to get the size to allocate statically.
struct fileStruct fileobjarray[totalfiles];
fileobjarray is a VLA array of size totalfiles of fileStruct structure. To allocate using malloc we can write:
struct fileStruct *fileobjarray = malloc(totalfiles * sizeof(*fileobjarray));
We would allocate memory for an array of totalfiles
elements, with each element of sizeof(*fileobjarray) = sizeof(struct fileStruct)
size. Sometimes calloc is more preferable call in C, as it protects (on some platforms) against overflow:
struct fileStruct *fileobjarray = calloc(totalfiles, sizeof(*fileobjarray));
And remember to free()
.
int getNumberOfFiles(char *path)
{
int totalfiles = 0;
DIR *d;
struct dirent *dir;
struct stat cstat;
d = opendir(path);
while(( dir = readdir(d)) != NULL) {
totalfiles++;
}
return totalfiles;
}
int main()
{
int totalfiles = getNumberOfFiles(".");
int i =0;
DIR *d;
struct dirent *dir;
d = opendir(".");
struct fileStruct *fileobjarray = calloc(totalfiles, sizeof(*fileobjarray));
if (fileobjarray == NULL) {
fprintf(stderr, "Error allocating memory!\n");
return -1;
}
struct stat mystat;
while(( dir = readdir(d)) != NULL) {
fileobjarray[i].filesize=mystat.st_size;
strcpy (fileobjarray[i].filename ,dir->d_name );
i++;
}
free(fileobjarray);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.