struct c动态分配内存

ant*_*009 2 c struct calloc

我正在使用结构,我想初始化最多10个端口.但是,当程序运行时它可能会少得多,我们直到运行时才知道.但是,这将是最大的.我之前从未做过像这样的结构,因为我通常使用calloc和delcare动态分配像这样的*ports作为值类型.

但是,我无法理解这一点

*ports[MAX_PORTS]. Am I creating 10 pointers that point to port objects?
Run Code Online (Sandbox Code Playgroud)

*ports = (struct port_t*) calloc(2, sizeof(*ports)); 
Run Code Online (Sandbox Code Playgroud)

看起来我正在分配一个指向免费商店分配的2个端口对象的指针?

我不明白为什么我使用带箭头操作符的点运算符?ports [0] - > port_id = 20; printf("port_id:%d \n",ports [0] - > port_id);

#include <stdio.h>
#include <stdlib.h>

#define MAX_PORTS 10

struct port_t
{
    int port_id;
    char name;
} *ports[MAX_PORTS];

int main(void)
{
    *ports = (struct port_t*) calloc(2, sizeof(*ports));

    ports[0]->port_id = 20;

    printf("port_id: %d\n", ports[0]->port_id);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

通常,我在传递过程中所做的是:

struct port_t
{
    int port_id;
    char name;
} *ports;

ports = (struct port_t*) calloc(2, sizeof(*ports));
Run Code Online (Sandbox Code Playgroud)

然后分配以下任一项.然而,之前的程序员已经声明了我在顶部显示的所有内容,因此我无法更改任何内容.

ports[0].port_id = 10;
ports->port_id = 10;
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议,

Rya*_*ham 7

你的第一个代码块有

struct port_t
{
    int port_id;
    char name;
} *ports[MAX_PORTS];
Run Code Online (Sandbox Code Playgroud)

这是一个指针数组.这意味着以后使用时

ports[0]->port_id
Run Code Online (Sandbox Code Playgroud)

你正在解引用数组中的第一个指针.还有一些丑陋的周围你实际上是calloc'ing的大小.你实际上用2的数组替换了10的数组.你在那里得到的东西通常是丑陋的,容易出错.

我相信你的意图更符合以下方面:

struct port_t
{
    int port_id;
    char name;
} *ports;

int main(void)
{
    *ports = (struct port_t*) calloc(2, sizeof(*ports));

    ports[0].port_id = 20;

    printf("port_id: %d\n", ports[0].port_id);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于你使用的是C99,如果你真的想通过使用C99的变量数组声明,你可以避免使用calloc()/ malloc().

port_t array_on_mains_stack[some_runtime_port_count];
ports = array_on_mains_stack;
Run Code Online (Sandbox Code Playgroud)

其中的诀窍是,因为它在堆栈上,它只能从该函数和它调用的任何函数中有效.一旦从该功能返回,它当然会被释放.


Jim*_*y J 6

*ports[MAX_PORTS]. Am I creating 10 pointers that point to port objects?
Run Code Online (Sandbox Code Playgroud)

是的,你正在制作十个指针

*ports = (struct port_t*) calloc(2, sizeof(*ports));
Run Code Online (Sandbox Code Playgroud)

......但这一行是无稽之谈.它与此相同:

ports[0] = (struct port_t*) calloc(2, sizeof(port_t));
Run Code Online (Sandbox Code Playgroud)

即.您正在设置第一个指针指向两个端口的足够内存.

对于这么小的东西,制作十个端口但不全部使用它们会更有意义:

#define MAX_PORTS 10

struct port_t
{
    int port_id;
    char name;
} ports[MAX_PORTS];

/* number of ports in use */
int numPorts = 0;

int main(void)
{
    numPorts = 3;
    for (int i=0; i<numPorts; i++) {
     ports[i].port_id = i;
     printf("port_id %d: %d\n", i, ports[i].port_id);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)