在这个问题上,有人在评论中建议我不要使用malloc的结果。即,我应该这样做:
int *sieve = malloc(sizeof(*sieve) * length);
而不是:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
为什么会这样?
在这个问题上,有人在评论中建议我不要使用malloc的结果。即,我应该这样做:
int *sieve = malloc(sizeof(*sieve) * length);
而不是:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
为什么会这样?
当前回答
对我来说,这里的结论是,在C语言中使用malloc是完全没有必要的,但是如果你使用了C语言,它不会影响malloc,因为malloc仍然会为你分配你请求的内存空间。另一个原因是人们进行选角的原因或原因之一,这是为了使他们能够用C或C++编译相同的程序。
可能还有其他原因,但几乎可以肯定的是,其他原因迟早会让你陷入严重的麻烦。
其他回答
在C语言中,不需要强制转换malloc的返回值。malloc返回的指向void的指针会自动转换为正确的类型。但是,如果您想用C++编译器编译代码,则需要强制转换。社区中的首选替代方案是使用以下方法:
int *sieve = malloc(sizeof *sieve * length);
另外,如果你改变了筛子的类型,你就不用担心改变表达式的右边。
正如人们所指出的那样,铸件是不好的。尤其是指针强制转换。
这取决于编程语言和编译器。如果在C中使用malloc,则无需键入cast,因为它会自动键入cast。然而,如果您使用的是C++,那么应该键入cast,因为malloc将返回void*类型。
void指针是泛型指针,C支持从void指针类型到其他类型的隐式转换,因此不需要显式类型转换。
然而,如果您希望相同的代码在不支持隐式转换的C++平台上完美兼容,则需要进行类型转换,因此这一切都取决于可用性。
正如其他人所说的,它不是C所必需的,而是C++所必需的。如果您认为要使用C++编译器编译C代码,无论出于何种原因,都可以使用宏,例如:
#ifdef __cplusplus
# define MALLOC(type) ((type *)malloc(sizeof(type)))
# define CALLOC(count, type) ((type *)calloc(count, sizeof(type)))
#else
# define MALLOC(type) (malloc(sizeof(type)))
# define CALLOC(count, type) (calloc(count, sizeof(type)))
#endif
# define FREE(pointer) free(pointer)
这样,您仍然可以以非常紧凑的方式编写它:
int *sieve = MALLOC(int); // allocate single int => compare to stack int sieve = ???;
int *sieve_arr = CALLOC(4, int); // allocate 4 times size of int => compare to stack (int sieve_arr[4] = {0, 0, 0, 0};
// do something with the ptr or the value
FREE(sieve);
FREE(sieve_arr);
它将为C和C++编译。
返回的类型为void*,可以将其转换为所需类型的数据指针,以便可以取消引用。