malloc an array of struct pointers vs array of structs

What's the difference between

struct mystruct *ptr = (struct test *)malloc(n*sizeof(struct test));


struct mystruct **ptr = (struct test *)malloc(n*sizeof(struct test *));

They both work fine, I'm just curious about the actual difference between the two. Does the first one allocate an array of structs, whereas the second one an array of struct pointers? The other way around? Also, which one has a smaller memory footprint?


The first allocates an array of struct, and the other allocates an array of pointers to struct. In the first case, you can write to fields by assigning ptr[0].field1 = value; right away, while in the second case you must allocate the struct itself before doing the actual writing.

It is OK to drop the cast of malloc result in C, so you could write

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++) {

Need Your Help

Issue with hiding a Modal - Bootstrap 3

javascript jquery twitter-bootstrap twitter-bootstrap-3

I cannot get a modal to hide after confirming a delete (closing works fine), thus I am trying to reference it by a modal ID now.

Using bootstrap twitter with google blogger

twitter-bootstrap blogger

I've been trying to use bootstrap twitter on my google blog on Apparently it is not working, and I am quite sure that the problem is how I am including the css and js files. I've uploa...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.