c - 尝试将整数参数传递给线程

标签 c multithreading

您好,我无法将整数参数传递给线程并使用该整数计算阶乘。这是我的代码。

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

void * factorial(void * number) {

    int factorial = 1;
    int counter = 1;

    int newnum = *((int*)number);
    printf("%d", newnum);

    pthread_exit(NULL);
}

void * sumup( void * number) {


}


int main(int argc, char *argv[]) {

    if(argc != 2) {
            printf("Argument number error\n");
            exit(1);
    }

    pthread_t thread1;
    pthread_t thread2;

    int i;
    for(i = 0; i < argc; i++){
            printf(argv[i]);
            printf("\n");
    }

    int rc;
    void * t = argv[1];
    rc = pthread_create(&thread1, NULL, factorial, (void*)t );
    if (rc != 0) {
            printf("There was an error creating the thread\n");
            exit(1);
    }

    pthread_exit(NULL);
    exit(0);

}

现在我只是想打印发送的整数以使其正常工作,但这是我的输出:

./任务1 5 1162608693

它应该打印出 5 而不是 1162608693

最佳答案

argv 表存储指向字符的指针。通过这样做:

void * t = argv[1];
int newnum = *((int*) t );

您尝试打印的是字符串“5”的整数值。您正在传递字符串的地址:

'5' '\0'

转换为指向 int 的指针,因此您尝试读取第一个 sizeof(int) 字节的整数值,结果是:

5 0 [and you read sizeof(int)-2 bytes out of range]

这会导致未定义的行为。

解决方案

要将作为参数传递给程序的字符串转换为整数,请使用 atoistrtol,它们可以更好地进行错误检查。

关于c - 尝试将整数参数传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535987/

相关文章:

java - Android的decodeByteArray在自己的线程上非常慢,但在UI线程上却不是

java - 阻塞当前线程执行,直到一个变量被另一个线程更新

c++ - Lua 模块从 DllMain 推送 C 函数

c - 简单的操作系统内核编程

c - 文本解析与 .和 : in ANSI C

java - 如何检查哪个线程(共 10 个)调用了 Singleton 构造函数?

Java/ Spring MVC : provide request context to child threads

Java 监视器 : How to know if wait(long timeout) ended by timeout or by Notify()?

c - 使用 fscanf 将固定长度的整数扫描到数组中

c - Xcode LLVM 纯 C 表达式