gpt4 book ai didi

c atoi() 函数不起作用

转载 作者:行者123 更新时间:2023-11-30 20:04:49 24 4
gpt4 key购买 nike

这是我的代码。 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com