指向结构体数组并获取内存 [英] Pointer to an array of structs and getting memory

查看:149
本文介绍了指向结构体数组并获取内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

link是指向节点的指针

typedef struct node * link;

在main()中,我有以下代码(config-> m只是一些整数):

In main(), I have the following code (config->m is just some integer):

// array of pointers to structs
link heads[config->m]; 

// make memory for head nodes
for(i = 0; i < config->m; i++)
  heads[i] = malloc(sizeof(struct node));

该代码有效(很棒). 但是有没有办法我可以分配config->m个内存而不循环呢?我尝试过

The code works (which is great). But is there a way I can allocate config->m pieces of memory without the loop? I tried

link heads[config->m];
heads = malloc(sizeof(struct node) * config->m);

但是我友好的邻居编译器告诉我incompatible types in assignment

but my friendly neighborhood compiler tells me incompatible types in assignment

我知道我可以使用

struct node heads[config->m];

但是我想用指针来做这些事情.

But I want to do this stuff with pointers.

和往常一样,有人会问我这是否是家庭作业的一部分,答案是肯定的.但是,这段特定的代码与实际的分配无关.这是出于我自己的启示.但是感谢您提出:|

And as always, someone will ask me if this is part of homework, and the answer is yes (sort of). But this particular chunk of code doesn't have anything to do with the actual assignment; it's for my own enlightenment. But thanks for asking :|

推荐答案

不是,您需要循环.您的heads数组本质上是一个二维数组.您至少需要两个分配.第一个是指针数组:

Nope, you need the loop. Your heads array is essentially a two dimensional array. You need at least two allocations. The first is the array of pointers:

link * heads = (link*)malloc (config->m * sizeof (link));

第二个是heads数组的每个成员指向的内存:

The second is the memory that each member of the heads array points to:

link buf = (link)malloc(sizeof(struct node) * config->m);
for(i = 0; i < config->m; i++)
    heads[i] = &buf[i];

然后取消分配:

free(heads);
free(buf);

这篇关于指向结构体数组并获取内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆