繁体   English   中英

Ctring转换中的分段错误

[英]segmentation Fault in C String conversion

下面是我的项目Euler的程序。 我试图将字符串转换为数字时出现分段错误;

main()
{
    char me[] = "731671765313306249";
    int counter = 0;
    unsigned int product = 0;
    unsigned int temp = 0;
    char dup_me[5];
    int j = 0;
    printf("\n The String is:%s", me);

    for(counter = 0; counter <= (strlen(me) - 5); counter ++)
    {
        temp = ((int)(me[counter]) * (int)(me[counter + 1]) * (int)(me[counter + 2]) * (int)(me[counter + 3]) * (int)(me[counter + 4]));
        if (product < temp)
        {
            product = temp;
            for(j = 0; j < 4; j ++)
            {

                dup_me[j] = me[counter + j];
                printf("\nThis time: %d", atoi(dup_me[j]));
            }
            dup_me[j+1] = '\0';
        }
    }
    printf("\n The products is ;%Ld", product);
    printf("The producted numbers are:%s", dup_me);
    return 0;
}

如果我评论这部分,它运行正常。

printf("\nThis time: %d", atoi(dup_me[j]));

我知道产品答案是对的。 它将字符转换为其ascii值。 我需要有关此分段错误的帮助。 我需要将该单个字符(数字)转换为整数值

键盘链接

谢谢

我认为你me[]可能无效。 如果你想用me作为缓冲区,请将其声明为char* me 通过为其分配一个空白字符串,您实际上只创建了一个没有存储空间的字符串。

函数atoi的原型如下: int atoi(const char *nptr)所以它需要一个指向char的指针,你给它一个char所以替换这一行: printf("\\nThis time: %d", atoi(dup_me[j]))使用此printf("\\nThis time: %d", atoi(&dup_me[j])); 一切都应该工作正常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM