標籤:參數 傳值 c語言
C語言中結構體作為函數參數,有兩種方式:傳值和傳址。
1.傳值時結構體參數會被拷貝一份,在函數體內修改結構體參數成員的值實際上是修改調用參數的一個臨時拷貝的成員的值,這不會影響到調用參數。在這種情況下,涉及到結構體參數的拷貝,程式空間及時間效率都會受到影響。
例子:
typedef struct tagSTUDENT{ char name[20]; int age;}STUDENT;void fun(STUDENT stu){ printf(“stu.name=%s,stu.age=%d/n”,stu.name,stu.age);}
2.傳指標時直接將結構體的首地址傳遞給函數體,在函數體中通過指標引用結構體成員,可以對結構體參數成員的值造成實際影響。效率高,常在大型項目中用到,如著名的開源構架Nginx中對於結構體的使用就是一個很好的例子。例子該會在最後給出。
C語言中數組作為函數參數,一般傳遞的是數組的首地址。因此在數組名作函數參數時所進行的傳送只是地址的傳送, 也就是說把實參數組的首地址賦予形參數組名。形參數組名取得該首地址之後,也就等於有了實在的數組。實際上是形參數組和實參數組為同一數組,共同擁有一段記憶體空間。例子同樣見下面Nginx的使用。
static ngx_command_t ngx_http_mytest_commands[] = { { ngx_string("mytest"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF|NGX_CONF_NOARGS, ngx_http_mytest, NGX_HTTP_LOC_CONF_OFFSET, 0, NULL }, ngx_null_command};static ngx_http_module_t ngx_http_mytest_module_ctx = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};ngx_module_t ngx_http_mytest_module = { NGX_MODULE_V1, &ngx_http_mytest_module_ctx,//結構體指標傳遞 ngx_http_mytest_commands,//數組預設地址傳遞 NGX_HTTP_MODULE, NULL, NULL, NULL, NULL, NULL, NULL, NGX_MODULE_V1_PADDING};
最後便於理解,給出ngx_module_t的定義
typedef struct ngx_module_s ngx_module_t;struct ngx_module_s { ngx_uint_t ctx_index; ngx_uint_t index; ngx_uint_t spare0; ngx_uint_t spare1; ngx_uint_t spare2; ngx_uint_t spare3; ngx_uint_t version; void *ctx; ngx_command_t *commands; ngx_uint_t type; ngx_int_t (*init_master)(ngx_log_t *log); ngx_int_t (*init_module)(ngx_cycle_t *cycle); ngx_int_t (*init_process)(ngx_cycle_t *cycle); ngx_int_t (*init_thread)(ngx_cycle_t *cycle); void (*exit_thread)(ngx_cycle_t *cycle); void (*exit_process)(ngx_cycle_t *cycle); void (*exit_master)(ngx_cycle_t *cycle); uintptr_t spare_hook0; uintptr_t spare_hook1; uintptr_t spare_hook2; uintptr_t spare_hook3; uintptr_t spare_hook4; uintptr_t spare_hook5; uintptr_t spare_hook6; uintptr_t spare_hook7;};
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
菜鳥學習-C語言函數參數傳遞詳解-結構體與數組