【问题标题】:C - pointer problems and void method problems [closed]C - 指针问题和 void 方法问题 [关闭]
【发布时间】:2013-05-03 22:09:35
【问题描述】:

我在 C 中的以下代码有问题。基本上我想创建两个线程并给它们两个整数值 "ergebnis" 。在此之后,线程应该必须单独计算这个值并打印它们各自的结果。

编译时出现以下错误:

3.2.c: In function ‘erhoehenumeins’:
3.2.c:10:13: warning: dereferencing ‘void *’ pointer [enabled by default]
3.2.c:10:13: error: void value not ignored as it ought to be
3.2.c: In function ‘verdoppeln’:
3.2.c:20:18: error: invalid operands to binary * (have ‘void *’ and ‘int’)   

代码:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void *erhoehenumeins(void * dummy) {
    printf("Thread erhoehenumeins() wurde gestartet\n");
    int temp;
    temp= dummy+1;
    printf("Thread erhoehenumeins() wurde beendet\n");
    printf("Ergebnis=%d\n",temp);
}
void *verdoppeln(void * dummy) {
    printf("Thread verdoppeln() wurde gestartet\n");
    int temp=dummy*2;
    printf("Thread verdoppeln() wurde beendet\n");
    printf("Ergebnis=%d\n",temp);
}

int main() {
    int ergebnis=3;
    pthread_t thread1, thread2;
    // Thread 1 erzeugen
    pthread_create( &thread1, NULL, &erhoehenumeins, &ergebnis );

    // Thread 2 erzeugen
    pthread_create( &thread2, NULL, &verdoppeln, &ergebnis );

    // Main-Thread wartet auf beide Threads.
    pthread_join( thread1, NULL );
    pthread_join( thread2, NULL );
    printf("\nHaupt-Thread main() wurde beendet\n");
    exit(0);
}

感谢您的帮助!

【问题讨论】:

  • 好吧,你不会从你的函数中返回任何东西......
  • 只是一个旁注:你的缩进(或者更确切地说是没有缩进)使得这比它需要的更难阅读。关于您的问题:pastebin.com/1XNrKfBc

标签: c pointers pthreads void


【解决方案1】:

排队

int temp=dummy*2;

dummy 的值是 void *——编译器不能将其乘以 2。

也许你应该这样做”

int temp = (*(int *)dummy)*2;

【讨论】:

  • 非常感谢您的快速回答。当我按照您的解释进行操作时,我得到了错误:3.2.c:在函数“verdoppeln”中:3.2.c:20:8:警告:赋值使指针从整数不进行强制转换[默认启用]
  • 我不明白为什么;也许您应该使用新代码编辑您的问题。
【解决方案2】:

这样做:

void * erhoehenumeins(void * dummy)
{
    int * p = (int *) dummy;
    ++*p;

    return NULL;
}

还有:

int ergebnis = 3;
pthread_create(&thread1, NULL, &erhoehenumeins, &ergebnis);

这当然是未定义的行为并且完全被破坏,但现在应该这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 2014-05-13
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多