试图将整数参数传递给线程

时间:2016-04-10 21:55:28

标签: 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 五 1162608693

它应该打印出5而不是1162608693

1 个答案:

答案 0 :(得分:1)

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进行更好的错误检查。

相关问题