1. 程式人生 > >菜鳥學習-C語言函式引數傳遞詳解-結構體與陣列

菜鳥學習-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;
};