结构体指针数组 vs 结构体数组

来源:互联网 发布:互联网信息过滤软件 编辑:程序博客网 时间:2024/06/16 12:11

文章内容来自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结构体的指针。

对于第二种情况,我们需要为每一个数组变量分配空间,如下:

[cpp] view plain copy
  1. struct mystruct **ptr = malloc(n*sizeof(struct test *));  
  2. for (int i = 0; i != n ; i++) {  
  3.     ptr[i] = malloc(sizeof(struct test));  
  4. }  
  5. ptr[0]->field1 = value;  
  6. ...  
  7. // Do not forget to free the memory when you are done:  
  8. for (int i = 0; i != n ; i++) {  
  9.     free(ptr[i]);  
  10. }  
  11. free(ptr);  

下面的使用方式是不正确的

[cpp] view plain copy
  1. struct mystruct **ptr = malloc(n*sizeof(struct test ));  
  2.   
  3. ptr[0]->filed1 = value;  
对于malloc而言,结构体和指针都是一样的,其都会将其转化为字节,所以上述这种用法不会自动将分配的内存转化为struct mystruct **。
0 0
原创粉丝点击