あなたのコードは、test_struct* の型である変数名「temp」を作成することです。次に、メモリを割り当て、変数 temp をそのメモリ ピースにポイントします。この一時変数は、malloc を使用して作成したメモリ ピースを指すポインタです。「temp」内には、2 つの変数名 data と next があります。C では、-> 演算子を使用してメンバーにアクセスします。(1 行目) 整数 5 を temp のデータ変数に保存します。2 行目で、next に NULL を割り当てます (この時点で、頭は null です [get it! your head is null :)])。次に、一時が指していたメモリピースに頭を向けます。printf("%d", head->data) を実行すると、5 が出力されます。
コードの各行にコメントを付けました。お役に立てれば。
#include <stdio.h>
#include <stdlib.h>
struct test_struct{
int data;
struct test_struct *next;
};
struct test_struct* head = NULL; //Creates a global variable head. its type is test_struct* and it is currently set to NULL
int main(){
head = NULL; //
struct test_struct* temp = (struct test_struct*)malloc(sizeof(struct test_struct));// creates a variable named temp which is a test_struct* type.
if(NULL==temp){ //at this point if temp is NULL, it imply that above line failed to allocate memory so there is no point executing this program so we return.
printf("error in memory");
return 0;
}
temp->data=5; // in the structure test_struct there is a member variable data inside it and since the temp variable is of type test_struct, temp also has data member. so we can access it by using -> operator. since data is a integer type we can assign a number to it.
temp->next=head; //At this point head is NULL. So we are pretty much assigning NULL to temp->next
head=temp; //When using link list we usually keep the head pointing to the beginning of the link list.(unless its a circular link list). This line does the exact same. It points the dead to memory piece that temp pointing to.
printf("%p\n",head);
return 0;
}