如何修复没有匹配功能来调用'ati'?

时间:2017-10-08 22:53:37

标签: c++ multithreading pthreads

我正在使用Pthreads API创建一个多线程C程序。我的程序基本上在main中创建一个单独的线程,称为runner,然后它将命令行argv [1]上提供的整数参数传递给runner。 Runner将所有值从1加到argv [1]。总之,全局变量打印在main中。

我收到以下错误:没有匹配函数来调用'ati'。

g++ -c -Werror main.cc
main.cc:30:14: error: no matching function for call to 'atoi'
        int upper = atoi(param);
                    ^~~~
/usr/include/stdlib.h:132:6: note: candidate function not viable: cannot convert
      argument of incomplete type 'void *' to 'const char *' for 1st argument
int      atoi(const char *);
         ^
1 error generated.
make: *** [main.o] Error 1

这是我的代码

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

int sum; /* this data is shared by the thread(s) */
void *runner(void *param); /* threads call this function */

int main(int argc, char *argv[]) {
    pthread_t tid; /* the thread identifier */
    pthread_attr_t attr; /* set of thread attributes */
    if (argc != 2) {
        fprintf(stderr,"usage: a.out <integer value>\n");
        return -1;
    }
    if (atoi(argv[1]) < 0) {
        fprintf(stderr,"%d must be >= 0\n",atoi(argv[1]));
        return -1;
    }
    /* get the default attributes */
    pthread_attr_init(&attr);
    /* create the thread */
    pthread_create(&tid,&attr,runner,argv[1]);
    /* wait for the thread to exit */
    pthread_join(tid,NULL);
    printf("sum = %d\n",sum);
} // end of main

/* The thread will begin control in this function */
void *runner(void *param) {
    int upper = atoi(param);
    int i;
    sum = 0;
    for (i = 1; i <= upper; i++) {
        sum += i;
    }
    pthread_exit(0);
} // end of runner

1 个答案:

答案 0 :(得分:-1)

就像评论中所说,问题是您将void *而不是char *传递给atoi()来电。

但是,如果您使用的是C ++,请使用以下代码:

int i;
std::istringstream ss(argv[1]);
ss >> i;
if (!ss.good()) {
  // Input was not a number...
} else {
  // Use i...
}

为什么呢?至少是因为:

  • 您可以检查转换是否成功(atoi()未检测到错误。)
  • C ++风格,而不是C风格
相关问题