简体   繁体   English

malloc指向数组的指针

[英]malloc pointer to array

int (*p)[2];
p=(int(*))malloc(sizeof(int[2])*100);

What is the right way to malloc a pointer to an array? malloc指向数组的指针的正确方法是什么? I can't figure out the part with (int(*)) 我无法找出(int(*))的部分

Posting comments as answer: 发表评论作为答案:
In C you should not to cast the return value of malloc . C你不应该转换malloc的返回值。 Please refer this post on SO for more information regarding why typecasting return value of malloc is not a good idea in C . 请参阅SO上的这篇文章 ,了解更多关于为什么在Cmalloc返回值进行类型转换不是一个好主意的信息。 And if for some reason you really really want to cast, it should be (int(*)[2]) . 如果由于某种原因你真的想要施放,它应该是(int(*)[2]) (int(*)) is int * . (int(*))int * The size passed to malloc looks fine (allocating size for 100 pointers to array of 2 ints). 传递给malloc的大小看起来很好(为100个指针分配大小为2个整数的数组)。 So you should be doing 所以你应该这样做

int (*p)[2];
p=malloc(sizeof(int[2])*100); 

Hope this helps! 希望这可以帮助!

It's not clear what you want here. 目前还不清楚你想要什么。 If you want 100 int pairs, for example, arranged as an array of pointers to int (where each pointer points to exactly two ints), then you need to call malloc 100 times on 100 pointers to int, allocating two integers each time. 如果你想要100个int对,例如,排列为指向int的指针数组(其中每个指针指向两个整数),那么你需要在100个指向int的指针上调用malloc 100次,每次分配两个整数。

It just doesn't' make sense to "malloc a pointer to an array". 它只是没有意义“malloc指向数组的指针”。 You can malloc an array, and assign that address to a pointer though, or you can malloc an array of pointers. 你可以malloc一个数组,并将该地址分配给指针,或者你可以malloc一个指针数组。 But what you've asked is not clear. 但你问的问题并不清楚。

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

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