C malloc

2018-07-05 11:20 更新

學(xué)習(xí)C - C malloc

你也可以顯式地在運(yùn)行時(shí)分配內(nèi)存。

你也可以顯式地在運(yùn)行時(shí)分配內(nèi)存。...

當(dāng)你使用 malloc()函數(shù),指定內(nèi)存的字節(jié)數(shù)你想要分配作為參數(shù)。

該函數(shù)返回它的內(nèi)存的第一個(gè)字節(jié)的地址分配響應(yīng)您的請(qǐng)求。

動(dòng)態(tài)內(nèi)存分配的一個(gè)典型示例可能是:

int *pNumber = (int*)malloc(100);

這里,您請(qǐng)求了100字節(jié)的內(nèi)存,并將此內(nèi)存塊的地址分配給pNumber。

以下代碼分配內(nèi)存以容納25個(gè)整數(shù)。

int *pNumber = (int*)malloc(25*sizeof(int));

(int *)將函數(shù)返回的地址轉(zhuǎn)換為int類型的指針。


#include <stdio.h> 
#include <stdlib.h> 
main() 
{ 
   char *name; 
   name = (char *) malloc(80*sizeof(char)); 
   if ( name != NULL ) { 
      printf("\nEnter your name: "); 
      gets(name); 
      printf("\nHi %s\n", name); 
      free(name); //free memory resources 
   }  // end if 
} //end main 

上面的代碼生成以下結(jié)果。



免費(fèi)和malloc

下面的代碼顯示了處理內(nèi)存分配失敗的模式。

int *pNumber = (int*)malloc(25*sizeof(int));
if(!pNumber)
{
  // Code to deal with memory allocation failure . . .
}

釋放動(dòng)態(tài)分配的內(nèi)存

當(dāng)動(dòng)態(tài)分配內(nèi)存時(shí),您需要在不再需要時(shí)釋放內(nèi)存。

要釋放內(nèi)存,只需寫下這條語句:

free(pNumber);
pNumber = NULL;

free()函數(shù)具有類型為 void * 的形式參數(shù),你可以傳遞任何類型的指針作為參數(shù)。


    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>

    int main(void)
    {
      unsigned long long *pPrimes = NULL;  // Pointer to primes storage area
      int total = 5;                       // Number of primes required

      // Allocate sufficient memory to store the number of primes required
      pPrimes = (unsigned long long*)malloc(total*sizeof(unsigned long long));

      if(!pPrimes){
         printf("Not enough memory.\n");
         return 1;
      }
      free(pPrimes);                      // Release the heap memory . . .
      pPrimes = NULL;                     // . . . and reset the pointer
      return 0;
   }

上面的代碼生成以下結(jié)果。



例子

在本節(jié)中,我們將使用指針創(chuàng)建一個(gè)動(dòng)態(tài)數(shù)組。

一般來說,我們可以聲明一個(gè)數(shù)組使用[]和size。 現(xiàn)在我們可以聲明動(dòng)態(tài)大小的數(shù)組。

基本上,當(dāng)我們添加一個(gè)新值時(shí),我們分配內(nèi)存,然后將其附加到數(shù)組。


  #include <stdio.h> 
  #include <stdlib.h> 

  int main(int argc, const char* argv[]) { 

    // define dynamic array of pointer 
    int *numbers; // single array pointer 

    // a number of array 
    int N = 10; 

    // allocate memory 
    numbers = malloc( N * sizeof(int)); 

    // set values 
    int i; 
    for(i=0;i<N;i++){ 
      numbers[i] = i+3; 
    } 

    // display values 
    for(i=0;i<N;i++){ 
        printf("%d ",numbers[i]); 
    } 
    printf("\n"); 

    // free memory 
    free(numbers); 

    return 0; 
  } 

上面的代碼生成以下結(jié)果。

注意

另一個(gè)示例,我們還定義了具有多維的動(dòng)態(tài)數(shù)組。

例如,我們創(chuàng)建二維動(dòng)態(tài)數(shù)組。


   #include <stdio.h> 
   #include <stdlib.h> 

   int main(int argc, const char* argv[]) { 

     // define dynamic array of pointer 
     int **matrix; // two dimensional array pointer 

     // a number of array 
     int M = 3; 
     int N = 5; 

     // allocate memory 
     matrix = malloc( M * sizeof(int*)); 

     // set values 
     int i,j; 
     for(i=0;i<M;i++){ 
       matrix[i] = malloc( N * sizeof(int)); 
       for(j=0;j<N;j++){ 
           matrix[i][j] = i + j; 
       } 
     } 

     // display values 
     for(i=0;i<M;i++){ 
         for(j=0;j<N;j++){ 
             printf("%d ",matrix[i][j]); 
         } 
         printf("\n"); 
     } 

     // free memory 
     free(matrix); 

     return 0; 
   } 

上面的代碼生成以下結(jié)果。

使用calloc()函數(shù)的內(nèi)存分配

在stdlib.h頭中聲明的 calloc()函數(shù)。

它提供了比 malloc()的幾個(gè)優(yōu)勢(shì)。

它將內(nèi)存分配為給定大小的元素?cái)?shù)。

它初始化分配的內(nèi)存,使所有字節(jié)為零。

calloc()函數(shù)需要兩個(gè)參數(shù)值:數(shù)據(jù)項(xiàng)的數(shù)量和每個(gè)數(shù)據(jù)項(xiàng)的大小。

兩個(gè)參數(shù)都是 size_t 類型。

分配的區(qū)域的地址返回類型void *。

這里是如何使用 calloc()為int類型的75個(gè)元素的數(shù)組分配內(nèi)存:

int *pNumber = (int*) calloc(75, sizeof(int));

如果不可能分配所請(qǐng)求的內(nèi)存,則返回值將為NULL。

你可以讓編譯器負(fù)責(zé)提供轉(zhuǎn)換:

int *pNumber = calloc(75, sizeof(int));

例子


    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>

    int main(void)
    {
      unsigned long long *pPrimes = NULL;  // Pointer to primes storage area
      int total = 5;                       // Number of primes required

      // Allocate sufficient memory to store the number of primes required
      pPrimes = calloc((size_t)total, sizeof(unsigned long long));
      if (pPrimes == NULL) {
           printf("Not enough memory. It"s the end I"m afraid.\n");
           return 1;
      }
      free(pPrimes);                      // Release the heap memory . . .
      pPrimes = NULL;                     // . . . and reset the pointer
      return 0;
   }

上面的代碼生成以下結(jié)果。

擴(kuò)展動(dòng)態(tài)分配的內(nèi)存

realloc()函數(shù)使您能夠重用或擴(kuò)展內(nèi)存您先前使用malloc()或calloc()(或realloc())分配。

realloc()函數(shù)需要兩個(gè)參數(shù)值:一個(gè)包含先前地址的指針通過調(diào)用malloc(),calloc()或realloc()返回,以及新內(nèi)存的大小(以字節(jié)為單位)。

例3

由malloc()獲取的各個(gè)內(nèi)存段可以像數(shù)組成員一樣處理;這些內(nèi)存段可以用索引引用。


#include <stdio.h> 
#include <stdlib.h> 
main() 
{ 
   int *numbers; 
   int x; 
   numbers = (int *) malloc(5 * sizeof(int)); 
   if ( numbers == NULL ) 
      return;  // return if malloc is not successful 
   numbers[0] = 100; 
   numbers[1] = 200; 
   numbers[2] = 300; 
   numbers[3] = 400;  
   numbers[4] = 500; 
   printf("\nIndividual memory segments initialized to:\n"); 
   for ( x = 0; x < 5; x++ ) 
      printf("numbers[%d] = %d\n", x, numbers[x]); 
}

上面的代碼生成以下結(jié)果。

例4

以下代碼顯示了擴(kuò)展的連續(xù)內(nèi)存和realloc()的結(jié)果。


#include<stdio.h> 
#include<stdlib.h> 
main() 
{ 
   int *number; 
   int *newNumber; 
   int x; 
   number = malloc(sizeof(int) * 5); 
   if ( number == NULL ) { 
      printf("\nOut of memory!\n"); 
      return; 
   }  // end if 
   printf("\nOriginal memory:\n"); 
   for ( x = 0; x < 5; x++ ) { 
      number[x] = x * 100; 
      printf("number[%d] = %d\n", x, number[x]); 
   }  // end for loop 
   newNumber = realloc(number, 10 * sizeof(int));  
   if ( newNumber == NULL ) { 
      printf("\nOut of memory!\n"); 
      return; 
   } 
   else 
      number = newNumber; 
   //intialize new memory only 
   for ( x = 5; x < 10; x++ ) 
      number[x] = x * 100; 
   printf("\nExpanded memory:\n"); 
   for ( x = 0; x < 10; x++ ) 
      printf("number[%d] = %d\n", x, number[x]); 
   //free memory 
   free(number); 
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)