首页 > 解决方案 > How can this function use a variable while defining it in calloc?

问题描述

This is an example usage from the man page of pthread_create.

I am interested in this line:

struct thread_info *tinfo = calloc(num_threads, sizeof(*tinfo));

In seems tinfo is declared here, but it's also used in the argument to calloc. Is this equivalent to the below snippet?

struct thread_info *tinfo;
tinfo = calloc(num_threads, sizeof(*tinfo));

I'm unsure how tinfo can be used before it's declared in the first snippet.

标签: c

解决方案


In the man entry for pthread_create, the struct thread_info is declared previously:

struct thread_info {    /* Used as argument to thread_start() */
           pthread_t thread_id;        /* ID returned by pthread_create() */
           int       thread_num;       /* Application-defined thread # */
           char     *argv_string;      /* From command-line argument */
       };

So, when calling calloc, the compiler knows the size of the struct. The code is equivalent to specify the following:

struct thread_info *tinfo = calloc(num_threads, sizeof(struct thread_info));

推荐阅读