ขอสอบถามเกี่ยวกับเรื่องการจองหน่วยความจำให้กับ pointer ด้วยคำสั่ง malloc หน่อยครับ
จากโค้ด ด้านล่าง
1) ผมสงสัยครับว่าเมื่อไหร่ เราถึงต้องใช้คำสั่ง malloc เพื่อจองหน่วยความจำให้กับพอยเตอร์
2)จากบรรทัดที่ 16 มีการจองพื้นที่หน่วยความจำให้ pointer root ก่อนใช้งาน แต่ในบรรทัดที่ 19 ตัวแปรพอยเตอร์ conductor ทำไมถึงไม่มีการใช้คำสั่ง malloc ในการจองหน่วยความจำก่อนการใช้งานครับ
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc( sizeof(struct node) ); //Line 16: จองพื้นที่สำหรับพอยเตอร์ root ด้วย malloc ก่อนนำไปใช้งาน
root->next = 0;
root->x = 12;
conductor = root; //Line 19: ยังไม่มีการจองพื้นที่สำหรับพอยเตอร์ conductor
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = 0;
conductor->x = 42;
return 0;
}
จองพื้นที่ให้ pointer ด้วยคำสั่ง malloc
จากโค้ด ด้านล่าง
1) ผมสงสัยครับว่าเมื่อไหร่ เราถึงต้องใช้คำสั่ง malloc เพื่อจองหน่วยความจำให้กับพอยเตอร์
2)จากบรรทัดที่ 16 มีการจองพื้นที่หน่วยความจำให้ pointer root ก่อนใช้งาน แต่ในบรรทัดที่ 19 ตัวแปรพอยเตอร์ conductor ทำไมถึงไม่มีการใช้คำสั่ง malloc ในการจองหน่วยความจำก่อนการใช้งานครับ
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc( sizeof(struct node) ); //Line 16: จองพื้นที่สำหรับพอยเตอร์ root ด้วย malloc ก่อนนำไปใช้งาน
root->next = 0;
root->x = 12;
conductor = root; //Line 19: ยังไม่มีการจองพื้นที่สำหรับพอยเตอร์ conductor
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = 0;
conductor->x = 42;
return 0;
}