Ctring转换中的分段错误

时间:2013-11-22 22:12:56

标签: c string

以下是项目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值。我需要有关此分段错误的帮助。我需要将该单个字符(数字)转换为整数值

The codepad link

由于

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

相关问题