0

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user3921
  • 241
  • 2
  • 3
  • 12
  • 3
    Try compiling with `-Wall` and `-Wextra` option. Did you see any warnings on this line? If yes, correct them. In cases like this, where you are not sure you are doing something in correct way, you should always obey the compiler. BTW, its not recommended to typecast the return value of `malloc`. – 0xF1 Jan 06 '14 at 08:45
  • 3
    By the way, don't cast the result of malloc in C plz ;) – dhein Jan 06 '14 at 08:47
  • 3
    [Don't cast the return value of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). – Some programmer dude Jan 06 '14 at 08:48
  • I was told to always cast malloc...anyway, does this declaration good for what im trying to do? I don't get any compiler warnings – user3921 Jan 06 '14 at 09:05
  • 1
    Except the useless cast, I don't see anything wrong in your code. – Michael M. Jan 06 '14 at 09:08
  • 1
    Using calloc(numOfUnits, sizeof(FILE*) ), this automatically initialize each byte to 0. – Peng Zhang Jan 06 '14 at 09:18

2 Answers2

1

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.

egur
  • 7,830
  • 2
  • 27
  • 47
  • yes of course, I am making sure that the input is larger 0. By the way, after the malloc and after im going over the FILE** arrOfFiles to open the files im seeing in debug that arrOfFiles points to null, is that making sense? – user3921 Jan 06 '14 at 09:24
  • You should check for a high number value too. If malloc succeed it should not point to NULL. – egur Jan 06 '14 at 09:35
1

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.

Community
  • 1
  • 1
KARTHIK BHAT
  • 1,410
  • 13
  • 23