c - 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.
解决方案
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));
推荐阅读
- sql - 将表中的值添加到另一个与文本框中的值相结合
- javascript - 如何在代码中使用preventdefault of jquery来防止key重复?
- java - RestTemplate 访问响应中的元素
- java - 如何使用正则表达式特定字符串拆分字符串
- python - 使用 nidaqmx-python 将模拟电压连续输出到 NI DAQ 模块
- java - Easymock.expect 抛出 IllegalStateException
- selenium - 我正在尝试为每个失败捕获屏幕截图,但 File.Utils 或 File.Handler 显示代码错误
- python - python - 如何使列表中的随机值至少在Python列表中的每个值的给定数量上是唯一的?
- c - 红黑树插入操作不断崩溃
- javascript - 如何解决 TypeError:无法将 null 转换为 int