乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      C語言使用回調(diào)函數(shù)解決內(nèi)存申請(qǐng)和釋放的問題

       orion360doc 2012-04-05

      C語言中,函數(shù)參數(shù)或者返回值中如果包含指針指向動(dòng)態(tài)分配的內(nèi)存區(qū)域,那么管理申請(qǐng)和釋放就顯得十分麻煩,一不小心就容易出錯(cuò),今天突發(fā)奇想借鑒高級(jí)語言函數(shù)式編程的思想,其實(shí)C語言里的函數(shù)指針已經(jīng)非常完美了,如果這樣寫,管理起來就會(huì)很方便,callback中無需關(guān)注buffer的釋放。

      01 #include <stdio.h>
      02 #include <stdlib.h>
      03 #include <string.h>
      04   
      05 // 回調(diào)函數(shù)
      06 // 使用這種技巧,在回調(diào)函數(shù)中就不用關(guān)注緩沖區(qū)的釋放了
      07 void callback(const char * buffer, int len) {
      08     int i;
      09     for (i = 0; i < len; i++) {
      10         putchar(buffer[i]);
      11     }
      12     putchar('\n');
      13 }
      14   
      15 void foo(void (* callback)(const char *, int)) {
      16     char * buffer;
      17     buffer = (char *)malloc(100);
      18     memset(buffer, 0, 100);
      19     strcpy(buffer, "Hello, World!");
      20     callback((const char *)buffer, strlen(buffer));
      21     free(buffer);
      22 }
      23   
      24 int main() {
      25     // 下面兩種方式都行,不知道為什么
      26     foo(&callback);
      27     foo(callback);
      28     return 0;
      29 }




      因?yàn)?amp;callback == callback

      void foo()可以寫成這樣比較清晰

      typedef void (* callbackPtr)(...) ;

      void foo(callbackPtr cb)() 

      {

      if (!cb) return; //還可以檢查空值

      ...

       cb(...);

      ...

      }

      這種寫法在win32里很常見,如CreateThread()就用到

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多