
授人以渔,不授人以鱼。
程序代码:
// crt_malloc.c
// This program allocates memory with
// malloc, then frees the memory with free.
#include <stdlib.h> // For _MAX_PATH definition
#include <stdio.h>
#include <malloc.h>
int main( void )
{
char *string;
// Allocate space for a path name
string = malloc( _MAX_PATH );
// In a C++ file, explicitly cast malloc's return. For example,
// string = (char *)malloc( _MAX_PATH );
if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
}



程序代码:#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
struct LNode *next;
int num;
float fl;
double du;
}LNode, *LinkList;
LNode* ApplyMem(LNode *head)
{
LNode *p;
int i, j;
i = sizeof(LinkList);
j = sizeof(LNode);
printf("%d %d\n", i, j); //输出的是i, j
if (NULL == head)
{
head = (LNode *)malloc(1 * sizeof(LinkList));
if (!head)
{
printf("Apply fail!\n");
return NULL;
}
}
head->next = NULL;
head->num = 1;
//head->ch = 'a';
head->fl = 1.2;
head->du = 22.0;
p = (LNode *)malloc(1 * sizeof(LinkList));
if (!p)
{
printf("Apply fail!\n");
return NULL;
}
p->num = 2;
//p->ch = 'b';
p->fl = 2.4;
p->du = 54.0435;
p->next = head->next;
head->next = p;
return head;
}
void FreeMem(LNode *head)
{
LNode *p;
while (NULL != head)
{
p = head;
head = head->next;
free(p);
}
}
void PrintList(LinkList head)
{
LinkList p;
p = head;
while (NULL != p)
{
printf("%d %f %f", p->num, p->fl, p->du);
p = p->next;
}
}
int main(void)
{
LNode *head = NULL;
head = ApplyMem(head);
PrintList(head);
//free(head);
head = NULL;
return 0;
}实验时先不释放。