C语言printf输出int*中的值的有关问题,linux gcc 4.8.2
C语言printf输出int*中的值的问题,linux gcc 4.8.2
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <pthread.h>
6 #include <sys/fcntl.h>
7 pthread_key_t key;
8 void *thread_fun1(void *arg)
9 {
10 printf("thread 1 start\n");
11 int a = 1;
12 pthread_setspecific(key, (void *)a);
13 sleep(2);
14 int *a1 = (int *)pthread_getspecific(key);
15 printf("thread 1 key->data is %d\n", *a1);
16 }
17
18 void *thread_fun2(void *arg)
19 {
20 printf("thread 2 start\n");
21 int a = 2;
22 pthread_setspecific(key, (void *)a);
23 int *a2 = (int *)pthread_getspecific(key);
24 printf("thread 2 key->data is %p\n", a2);
25 }
26
27 int main()
28 {
29 pthread_t tid1, tid2;
30 pthread_key_create(&key, NULL);
31
32 if(pthread_create(&tid1, NULL, thread_fun1, NULL))
33 {
34 printf("create new thread 1 failed\n");
35 return -1;
36 }
37 if(pthread_create(&tid2, NULL, thread_fun2, NULL))
38 {
39 printf("create new thread 2 failed\n");
40 return -1;
41 }
42 pthread_join(tid1, NULL);
43 pthread_join(tid2, NULL);
44 pthread_key_delete(key);
45 return 0;
46 }
~
~
这段代码中thread_fun1中为什么a1,能输出指针指向的值,而采用*a1就会报错。*a1里存的不是应该是指针指向的值,而a1里存的是地址吗。如果这样是正确的,那输出a1里存的地址,应该如何做
------解决思路----------------------
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <pthread.h>
6 #include <sys/fcntl.h>
7 pthread_key_t key;
8 void *thread_fun1(void *arg)
9 {
10 printf("thread 1 start\n");
11 int a = 1;
12 pthread_setspecific(key, (void *)a);
13 sleep(2);
14 int *a1 = (int *)pthread_getspecific(key);
15 printf("thread 1 key->data is %d\n", *a1);
16 }
17
18 void *thread_fun2(void *arg)
19 {
20 printf("thread 2 start\n");
21 int a = 2;
22 pthread_setspecific(key, (void *)a);
23 int *a2 = (int *)pthread_getspecific(key);
24 printf("thread 2 key->data is %p\n", a2);
25 }
26
27 int main()
28 {
29 pthread_t tid1, tid2;
30 pthread_key_create(&key, NULL);
31
32 if(pthread_create(&tid1, NULL, thread_fun1, NULL))
33 {
34 printf("create new thread 1 failed\n");
35 return -1;
36 }
37 if(pthread_create(&tid2, NULL, thread_fun2, NULL))
38 {
39 printf("create new thread 2 failed\n");
40 return -1;
41 }
42 pthread_join(tid1, NULL);
43 pthread_join(tid2, NULL);
44 pthread_key_delete(key);
45 return 0;
46 }
~
~
这段代码中thread_fun1中为什么a1,能输出指针指向的值,而采用*a1就会报错。*a1里存的不是应该是指针指向的值,而a1里存的是地址吗。如果这样是正确的,那输出a1里存的地址,应该如何做
------解决思路----------------------
pthread_setspecific(key, (void *)(&a));