user3921
user3921

Reputation: 241

How to declare a dynamic array of pointers to files

Im trying to create dynamically an array of pointers to files. The user is requested to input an integer number to be used for size and I need to create an array of pointers with that size.

 FILE** arrOfFiles = NULL;
 printf("Enter the number of units\n");
 scanf("%d", &numOfUnits);
 arrOfFiles = (FILE**)malloc(sizeof(FILE*)*numOfUnits);

is that declaration good for what im trying to do? I just wan't to make sure. Thanks.

Upvotes: 0

Views: 161

Answers (2)

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

There's no need to cast in pure C. CHeck this

so as long as this code is not ported to C++ it will work fine without cast.

Upvotes: 1

egur
egur

Reputation: 7960

You need to check the value of numOfUnits to be in the range (1, some_number) and only call malloc if the number is reasonable.

Like the comments said, no need to cast the return value of malloc in C. If this code will be ported to C++, you'll need the cast.

Upvotes: 1

Related Questions