c atoi() 函数不起作用

标签 c debugging atoi

这是我的代码。 findMin() 函数中的语句 int value=atoi(ptr[index]) 给出错误,如屏幕截图所示。

enter image description here

奇怪的是,当我在 main 中使用相同的 atoi() 函数时,一切都工作得很好,但在 findMin 中却尖叫起来!

CODE:
void* findMin(void *param); 

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

    pthread_t t2; //for min
    num=argc;

    /*int index=1; THIS WORKS 
    int value=atoi(argv[index]);*/

    //creating worker thread
    pthread_create(&t1,NULL,findMin,argv);

    pthread_join(t2,NULL); //wait for min
    printf("The minimum value is %d\n",min);


    return 0;
}

void* findMin(void *param) 
{
    char *ptr=(char *) param; //casting 
    int index=1;
    min=ptr[1];
    for(index; index<num; index++)
    {
         int value=atoi(ptr[index]); //THIS SCREAMS LIKE HELL!
         if(comp<min) min=value;

    }
}

最佳答案

查看atoi的签名:

int atoi(const char *);

该函数期望参数的类型为char *。您正在传递 ptr[index],其类型为 char
简单的解决方案是使用局部变量:

char digit[2] = "";

然后将第一个字符设置为你要处理的值:

digit[0] = ptr[index];
int value = atoi(digit);

因为digit的类型是char[],所以在传递给函数时它会衰减为指针

<小时/>

但这会很困惑。有一个更简单的方法。 C 标准要求数字字符是连续的,因此将数字字符转换为其整数值的常见技巧是这样写:

int value = ptr[index] - '0';

这是可行的,因为以 ASCII 为例,'0' 的数值是 48,'1' 是 49,2 是 50,依此类推。因此,如果您有这样的字符串:

"1234"

然后迭代每个字符,从每个字符中减去 '0',您将得到:

49 - 48 = 1
50 - 48 = 2
51 - 48 = 3
52 - 48 = 4

基本上做你想要/需要的事情

<小时/>

坚持下去

我刚刚注意到您实际上是在迭代argv。您的 Actor 不正确!

char *ptr=(char *) param;

实际上应该是:

char **ptr = param;

因为argv是一个char **(指向指针的指针)。

你还在这里做了一些奇怪的事情:

如果您实际上想要做的是比较传递的所有参数并从中选择最小的数字,那么这就是您应该编写的内容:

char **ptr= param; //no need for cast, void * is compatible with char **
int i = 1;
min = atoi(ptr[1]);//assuming min is int, because you're assigning value to it later on
for(i; i<num; ++i)
{
     int value = atoi(ptr[i]);
     if(value < min)//replaced comp with value, because I can't see the comp variable anywhere
         min = value;
}

关于c atoi() 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184742/

相关文章:

c - 使用atoi,从字符串中获取整数

c++ - 为什么这个IO操作会无限循环呢?

c - 使用 sscanf() 基于分隔符读取多个字符串

c# - Visual Studio 丢失/移动了我的断点

visual-studio - 如何在 Visual Studio 2008 中取消隐藏调试 -> 附加到进程?

c - 对文件内容使用 atoi() 时出现意外结果,按字符读取字符

c - `volatile` 是否足以让编译器处理对读取有副作用的机器寄存器?

c - post increment和post decrement运算符在c语言运算符优先级规则中有什么位置

c - 我以前从未见过加密。这个 C 加密片段有什么作用?

Python Pdb 给我一个回溯并且无法运行