文章内容来自StackOverFlow,文章在这里。
下面两个数组的区别是什么?
1.struct mystruct *ptr = (struct test *)malloc(n*sizeof(struct test));
and
2.struct mystruct **ptr = (struct test *)malloc(n*sizeof(struct test *));
第一个创建包含n个test结构的数组,第二个创建包含n个指向struct test结构体的指针。
对于第二种情况,我们需要为每一个数组变量分配空间,如下:
struct mystruct **ptr = malloc(n*sizeof(struct test *));
for (int i = 0; i != n ; i++) {
ptr[i] = malloc(sizeof(struct test));
}
ptr[0]->field1 = value;
...
// Do not forget to free the memory when you are done:
for (int i = 0; i != n ; i++) {
free(ptr[i]);
}
free(ptr);
下面的使用方式是不正确的
struct mystruct **ptr = malloc(n*sizeof(struct test ));
ptr[0]->filed1 = value;对于malloc而言,结构体和指针都是一样的,其都会将其转化为字节,所以上述这种用法不会自动将分配的内存转化为struct mystruct **。

本文详细解释了C++中数组和指针的区别,并提供了正确使用数组和指针的方法,避免常见错误。通过实例演示如何为数组和指针分配内存,以及如何安全地管理内存资源。
2074

被折叠的 条评论
为什么被折叠?



