2016-03-28 125 views
1
#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); 
} 

嗨!我正在嘗試爲一個頂點數組malloc。當我運行該程序時,它沒有打印出任何內容,並說程序已停止運行。但是,如果我只給了vertexList [0] - > id而不是vertexList [0] - > str並且只打印vertexList [0]的值,它會打印出「id爲5」...然後程序仍然停止。所以我認爲我做了malloc部分的錯誤? :/提前感謝您的幫助!Malloc結構指針錯誤

+0

您爲'size ** **指針的** malloc空間**(typedef的樂趣)並且指針未初始化;他們指向沒有(或者他們指向任何東西,如果你喜歡) – wildplasser

+1

1)不要'typedef'指針。 2)不要在C中投入'malloc'&friends或'void *'的結果。 – Olaf

回答

5

做一個指針類型的typedef通常是一個壞主意,因爲你不知道什麼是指針,什麼不是,最終搞亂了內存管理。

忽略Vertex的typedef,只是做:

struct vertex_t* vertexList = malloc(size * sizeof(struct vertex_t)); 

一切將結合在一起的。

如果你認爲struct vertex_t是非常詳細,你可以這樣做:

typedef struct vertex_t Vertex; 
Vertex *vertexList = malloc(size * sizeof(Vertex)); 

注意如何我的typedef並不能掩蓋一個指針,只有一個結構。