cpp初始化一个结构体

一开始我是直接定义一个结构体指针,给其进行初始化,但是一直报错,最后改为结构体后就好了
结构体定义:

struct graph
{
    // Number of edges in the graph
    int num_edges;
    // Number of vertices in the graph
    int num_nodes;

    // The node reached by vertex i's first outgoing edge is given by
    // outgoing_edges[outgoing_starts[i]].  To iterate over all
    // outgoing edges, please see the top-down bfs implementation.
    int* outgoing_starts;
    Vertex* outgoing_edges;

    int* incoming_starts;
    Vertex* incoming_edges;
};

using Graph = graph*;

正确初始化:

int node = 10;
int edge = 25;
struct graph g;
g.num_nodes = node;
g.num_edges = edge;

g.outgoing_starts = new int[node];
g.incoming_starts = new int[node];

g.outgoing_edges = new Vertex[edge];
g.incoming_edges = new Vertex[edge];

int outgoing_starts_tmp[node] = {0, 4, 7, 9, 11, 13, 15, 17, 22, 24};
int incoming_starts_tmp[node] = {0, 3, 5, 7, 12, 12, 15, 17, 19, 21};

Vertex outgoing_edges_tmp[edge] = {1, 2, 5, 7, 0, 3, 7, 0, 3, 6, 9, 2, 5, 3, 8, 3, 9, 0, 1, 3, 8, 9, 5, 9, 6};
Vertex incoming_edges_tmp[edge] = {1, 2, 7, 0, 7, 0, 4, 1, 2, 5, 6, 7, 0, 4, 8, 3, 9, 0, 1, 5, 7, 3, 6, 7, 8};

memcpy(g.outgoing_starts, outgoing_starts_tmp, sizeof(outgoing_starts_tmp));
memcpy(g.incoming_starts, incoming_starts_tmp, sizeof(incoming_starts_tmp));

memcpy(g.outgoing_edges, outgoing_edges_tmp, sizeof(outgoing_edges_tmp));
memcpy(g.incoming_edges, incoming_edges_tmp, sizeof(incoming_edges_tmp));

错误的方式(定义了结构体指针):

Graph g;
g->num_nodes = node;
g->num_edges = edge;

g->outgoing_starts = new int[node];
g->incoming_starts = new int[node];

g->outgoing_edges = new Vertex[edge];
g->incoming_edges = new Vertex[edge];

int outgoing_starts_tmp[node] = {0, 4, 7, 9, 11, 13, 15, 17, 22, 24};
int incoming_starts_tmp[node] = {0, 3, 5, 7, 12, 12, 15, 17, 19, 21};

Vertex outgoing_edges_tmp[edge] = {1, 2, 5, 7, 0, 3, 7, 0, 3, 6, 9, 2, 5, 3, 8, 3, 9, 0, 1, 3, 8, 9, 5, 9, 6};
Vertex incoming_edges_tmp[edge] = {1, 2, 7, 0, 7, 0, 4, 1, 2, 5, 6, 7, 0, 4, 8, 3, 9, 0, 1, 5, 7, 3, 6, 7, 8};

memcpy(g->outgoing_starts, outgoing_starts_tmp, sizeof(outgoing_starts_tmp));
memcpy(g->incoming_starts, incoming_starts_tmp, sizeof(incoming_starts_tmp));

memcpy(g->outgoing_edges, outgoing_edges_tmp, sizeof(outgoing_edges_tmp));
memcpy(g->incoming_edges, incoming_edges_tmp, sizeof(incoming_edges_tmp));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值