-3

请有人可以向我的 adlers 大脑解释为什么炖牛肉不等于 123.222?

为了解释 goulash 是为每个线程设置为 123.222 的指针变量,但是当线程被激活并通过线程函数空指针传递指针时,每个线程的输出可悲的是 0 而不是应该的 123.222。

代码:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>


typedef struct
{

int blossom;
double goulash;

}juniper;

juniper **jeffery;
juniper **james;

typedef struct{

int rodent_teeth;
juniper **raymond;

}rosebud;


void * thread_function(void *p){

juniper *monty = (juniper *) p;

printf("Goulash = %f\n",monty->goulash);

}


int main(){

int i;
rosebud *hattys_friend;

hattys_friend = (rosebud*) calloc(1,sizeof(rosebud));

hattys_friend->raymond = (juniper**) calloc(10,sizeof(juniper*));

for(i=0;i<10;i++){
hattys_friend->raymond[i] = (juniper*) calloc(10,sizeof(juniper));
        }

hattys_friend->raymond[2]->goulash = 5.6;

pthread_t threads[10];

for(int i=0;i<10;i++){

hattys_friend->raymond[i]->goulash = 123.222;
hattys_friend->rodent_teeth = i;

pthread_create(&threads[i],NULL,thread_function,(void*) &hattys_friend->raymond[i]);

printf("creating thread %d\n",i);

}

for(int i=0;i<10;i++){

pthread_join(threads[i],NULL);


}





jeffery = &hattys_friend->raymond[2];

james = hattys_friend->raymond;






printf("jeffery -> goulash = %f\n",(*jeffery)->goulash);


printf("james -> goulash = %f\n",(*(james+2))->goulash);

hattys_friend->raymond[2]->goulash = 1.6;

printf("james -> goulash = %f\n",(*(james+2))->goulash);


}
4

2 回答 2

4
void * thread_function(void *p){
    juniper *monty = (juniper *) p;
    printf("Goulash = %f\n",monty->goulash);
}

thread_function希望收到一个juniper*,但是

pthread_create(&threads[i],NULL,thread_function,(void*) &hattys_friend->raymond[i]);

hattys_friend->raymond[i]已经是 a juniper*,所以你传递给它 a juniper**,并且访问monty->goulash是未定义的行为。

于 2012-09-29T20:02:51.430 回答
0

问题是您将指向对象的指针传递juniper给线程。但是,在线程启动例程中,您将此指针转换为指向juniper. 这是未定义的行为。

于 2012-09-29T20:07:42.923 回答