【问题标题】:Is this a valid method of creating an array in C?这是在 C 中创建数组的有效方法吗?
【发布时间】:2012-11-18 02:05:22
【问题描述】:
int threads = 5;

pthread_t * thread = malloc(sizeof(pthread_t)*threads);

            for (i = 0; i < threads; i++){
                int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);}

我现在无法运行代码。但是我将其视为在线示例的一部分,并且对完全没有方括号感到有些困惑。我不太擅长 C。

那么这对创建线程数组有用吗?

【问题讨论】:

  • 假设你检查 malloc() 结果是否为 NULL,当然,虽然我更喜欢使用 (thread+i) 而不是 &amp;thread[i],你可以只使用 foobar_function,因为它的地址是隐含的,没有参数列表或括号。 .
  • pthread_t thread[5];差不多,所以是的。没问题。 pthread_create() 不关心句柄是在堆栈上还是在堆上创建的。

标签: c arrays multithreading


【解决方案1】:

是的。

thread 指向由malloc 分配的内存块,该内存块足够容纳threads pthread_t 对象。

threadspthread_t 对象的数组可以完全用这种方式表示。

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    相关资源
    最近更新 更多