Rio*_*Rio 1 c malloc struct pointers
#include <stdio.h>
#include <stdlib.h>
typedef struct vertex_t* Vertex;
struct vertex_t {
int id;
char *str;
};
int main(int argc, char* argv[])
{
int size = 10;
Vertex* vertexList = (Vertex*)malloc(size * sizeof(Vertex));
vertexList[0]->id = 5;
vertexList[0]->str = "helloworld";
printf("id is %d", vertexList[0]->id);
printf("str is %s", vertexList[0]->str);
return(0);
}
Run Code Online (Sandbox Code Playgroud)
嗨!我正在尝试使用malloc来获取Vertex数组.当我运行该程序时,它没有打印出任何内容,并说该程序已停止运行.但是如果我只给了vertexList [0] - > id而不是vertexList [0] - > str并且只打印了vertexList [0]的值,它会打印出"id is 5"......然后程序停止运行.所以我觉得我对malloc部分做错了什么?:/提前谢谢你的帮助!
做一个指针类型的typedef通常是一个坏主意,因为你不知道什么是指针,什么不是,你最终弄乱了内存管理.
忽略Vertextypedef,然后执行:
struct vertex_t* vertexList = malloc(size * sizeof(struct vertex_t));
Run Code Online (Sandbox Code Playgroud)
其他一切都会融合在一起.
如果您认为这struct vertex_t是非常冗长的,您可以这样做:
typedef struct vertex_t Vertex;
Vertex *vertexList = malloc(size * sizeof(Vertex));
Run Code Online (Sandbox Code Playgroud)
注意我的typedef如何不隐藏指针,只隐藏结构.