我承认这三个词都有不同的含义。但是,我不明白这些都适用于哪些特定的情况。有没有人能分享其中每一个的例子?谢谢。
malloc(sizeof(int))
malloc(sizeof(int *))
(int *)malloc(sizeof(int))发布于 2013-03-20 23:10:05
最简单的语法模式是:
int *p;
p = malloc (cnt * sizeof *p);此语法不会强制您更改代码,如果类型(和或大小...)*p变化的数量,例如在
struct mysstruct *q;
q = malloc (cnt * sizeof *q);这将避免像这样的问题
struct mysstruct *z;
z = malloc (cnt * sizeof(struct hisstruct)); // Auch!,另外:sizeof expr表单也更短。
更新:为了演示p = malloc(CNT * sizeof *p)这个测试程序的正确性:
#include <stdio.h>
#include <stdlib.h>
struct mystruct {
int i;
char s[14];
};
int main(void)
{
struct mystruct *p;
size_t siz;
siz = sizeof p;
printf("Sizeof p := %zu\n", siz);
siz = sizeof *p;
printf("Sizeof *p := %zu\n", siz);
printf("Allocating %zu (%u structs, each of size %zu) bytes to be assigned to p...\n"
, 10u * sizeof *p
, 10u, sizeof *p
);
p = malloc(10 * sizeof *p);
return 0;
}下面的输出如下:
Sizeof p := 8
Sizeof *p := 20
Allocating 200 (10 structs, each of size 20) bytes to be assigned to p...https://stackoverflow.com/questions/15222774
复制相似问题