简体   繁体   English

如何声明一个指向文件的动态指针数组

[英]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. 谢谢。

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. 您需要检查numOfUnits的值是否在范围(1,some_number)中,如果数字合理,则只调用malloc。

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. 就像评论所说的那样,不需要在C中强制转换malloc的返回值。如果将此代码移植到C ++中,则需要使用强制转换。

There's no need to cast in pure C. CHeck this 有没有必要在纯C.投选中此

so as long as this code is not ported to C++ it will work fine without cast. 所以只要这段代码没有移植到C ++,它就可以正常工作而不需要强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM