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結構指針錯誤
您爲'size ** **指針的** malloc空間**(typedef的樂趣)並且指針未初始化;他們指向沒有(或者他們指向任何東西,如果你喜歡) – wildplasser
1)不要'typedef'指針。 2)不要在C中投入'malloc'&friends或'void *'的結果。 – Olaf