您好,我无法将整数参数传递给线程并使用该整数计算阶乘。这是我的代码。
#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]
这会导致未定义的行为。
解决方案
要将作为参数传递给程序的字符串转换为整数,请使用 atoi
或 strtol
,它们可以更好地进行错误检查。
关于c - 尝试将整数参数传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535987/