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);
}
こんにちは!私はVertexの配列をmallocしようとしています。私がプログラムを実行すると、何も出力されず、プログラムが実行を停止したことが示されます。しかし、vertexList [0] - > idではなく、vertexList [0] - > strではなく、vertexList [0]だけを出力した場合、 "id is 5"というメッセージが出力されます。だから、私はmallocの部分に何か問題があったと思いますか? :/助けを先にありがとう!Malloc構造体ポインタエラー
あなたは 'size'のためのmalloc空間**ポインタ**(typedefsの喜び)そしてポインタは初期化されていません。彼らは何も指していません(あるいは、あなたが好きなら何でも指しています)。 – wildplasser
1)ポインタを 'typedef'しないでください。 2)一般的に 'malloc'と' friend'の結果や 'void *'の結果をC言語でキャストしないでください。 – Olaf