[英]Pthread struct argument with void*
Hy, HY,
I was wondering if something like this is possible, without using heap(malloc/calloc) Suppose I have a struct like this: 我想知道是否可以在不使用heap(malloc / calloc)的情况下实现这样的功能?假设我有一个这样的结构:
typedef struct {
void* par1_;
void* par2_;
}parameters;
and another one for position: 另一个职位:
typedef struct {
short x;
short y;
}position;
This is a function that gets called by the thread. 这是一个被线程调用的函数。
void* car(void* arg)
{
parameters car_type = *((parameters*) arg);
int first_par = *(int*)&car_type.par1_;
int second_par = *(int*)&car_type.par2_; // can I do this?
//if yes how do I extract now values from position struct "pos.x and pos.y"
}
From my main thread I want to mark position in the struct "position", assign that struct to the second parametar "par2_", and than send that to my function car. 我想从我的主线程中标记“ position”结构中的位置,将该结构分配给第二个参数“ par2_”,然后将其发送给我的功能车。
int main()
{
parameters pars;
position pos;
pos.x = 44;
pos.y = 25;
pars.par1_ = (void*) CAR_TYPE; // Global Variable
pars.par2_ = &pos; // not sure about this?
pthread_t tid;
pthread_create(&tid, NULL, car, (void*) &pars);
pthread_join(tid, NULL);
I'm sorry if this is a stupid question. 抱歉,这是一个愚蠢的问题。 Obviously I'm new to all this.
显然,我是新手。 Once again, I do not want to use heap.
再一次,我不想使用堆。 This is minimal example of my program.
这是我程序的最小示例。
I think you want something more like this; 我想你想要更多这样的东西;
void* car(void* arg)
{
parameters car_type = *((parameters*) arg);
int first_par = car_type.par1_; // This is CAR_TYPE is it really an int?
position *second_par = (position *)car_type.par2_;
second_par->x, second_par->y;
}
Although you might just want to change your parameters struct to include the types you really want. 尽管您可能只想更改参数结构以包含您真正想要的类型。
typedef struct {
int par1_;
position* par2_;
}parameters;
void* car(void* arg)
{
parameters car_type = *((parameters*) arg);
int first_par = car_type.par1_; // This is CAR_TYPE is it really an int?
car_type.par2_->x; //access like this
}
Not sure what you're asking, so I'll give you standard advice that seems like it pertains to the situation. 不知道您要问什么,所以我会给您标准建议,似乎与情况有关。
Be very careful when passing pointers to stack memory. 将指针传递到堆栈存储器时要非常小心 。 Always keep these three things in mind:
请始终牢记以下三点:
To reiterate: 重申:
Do: 做:
#include <stdio.h>
int main(int argc, char *argv[]) {
int nums = {12, 630, 43, 0};
printf("%d", sum(nums));
}
int sum(int *num_pointer) {
int count = 0;
for (; *num_pointer; num_pointer += 1) {
add(&count, *num_pointer);
}
return count;
}
void add(int *a, int b) {
*a += b;
}
Don't: 别:
int main(int argc, char *argv[]) {
print_int(get_int(7));
}
int *get_int(int value) {
return &value;
}
void print_int(int *num) {
printf("%d", *num);
}
Also, don't type-cast when you don't have to. 另外,在不需要时也不要键入。 It's a big sign pointing towards bad program design;
这是一个糟糕的程序设计的重要信号。 consider revising it.
考虑修改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.