有人能告诉我为什么我的代码会在SPOJ上产生一个分割吗?什么是分割错误?(fctrl - 2)

时间:2022-03-20 16:54:53
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
char arr[200],res[200];
char table[150][200];

string multiply(char n[],int m)
{
    int N=strlen(n),M,temp=0,x=0;
    for(int i=0;i<N;i++)
       arr[i]=n[N-1-i];
    for(int i=0;i<N;i++)
    {
        x=m*(arr[i]-'0')+temp;
        x=m*(arr[i]-'0')+temp;
        arr[i]=(x%10)+'0';
        temp=x/10;
    }
    while(temp>0)
    {
        arr[N]=(temp%10)+'0';
        temp/=10;
        N++;
    }
    M=strlen(arr);
    for(int i=0;i<M;i++)
       res[i]=arr[M-1-i];
}
void make_table()
{
    table[0][0]='1';
    for(int i=1;i<101;i++)
    {
        multiply(table[i-1],i);
        int u=strlen(res);
        for(int j=0;j<u;j++)
        {
            table[i][j]=res[j];
        }
    }
}
int main()
{
    int tc,n;
    scanf(" %d",&tc);
    make_table();
    while(tc--)
    {
        scanf(" %d",&n);
        printf("%s\n",&table[n]);
    }
    return 0;
}

That's my code for this problem : http://www.spoj.pl/problems/FCTRL2/ It generates correct answers for me but when i submit it , it tells me Runtime error(segmentation fault) . Can anyone explain to me what is the segmentation fault? cause i read it on the spoj website and i didn't understand how to avoid it and how to upgrade my code?

这是我对这个问题的代码:http://www.spoj.pl/problems/FCTRL2/它为我生成正确的答案,但当我提交时,它会告诉我运行时错误(分段错误)。有人能给我解释一下什么是分割错误吗?因为我在spoj网站上读到它,我不知道如何避免它,如何升级我的代码?

1 个解决方案

#1


2  

If you replace the return type of the function multiply from string to void the segfault is gone.

如果您将函数的返回类型替换为从字符串到void,那么segfault就消失了。

A segmentation fault happens when you try to read/write memory you don't have access to. For instance you can try writing on read only memory, or reading at address 0x00000000. A common way to achieve segfaults is by using an uninitialized pointer.

当你试图读/写你无法访问的内存时,会出现一个分段错误。例如,您可以尝试在只读存储器上编写,或者在地址0x00000000上读取。实现segfault的一种常见方法是使用未初始化的指针。

A debugger is often a good help to find a segmentation fault, as it will stop and show you where is happened.

调试器通常是找到分割错误的好帮手,因为它会停下来告诉你发生了什么。

#1


2  

If you replace the return type of the function multiply from string to void the segfault is gone.

如果您将函数的返回类型替换为从字符串到void,那么segfault就消失了。

A segmentation fault happens when you try to read/write memory you don't have access to. For instance you can try writing on read only memory, or reading at address 0x00000000. A common way to achieve segfaults is by using an uninitialized pointer.

当你试图读/写你无法访问的内存时,会出现一个分段错误。例如,您可以尝试在只读存储器上编写,或者在地址0x00000000上读取。实现segfault的一种常见方法是使用未初始化的指针。

A debugger is often a good help to find a segmentation fault, as it will stop and show you where is happened.

调试器通常是找到分割错误的好帮手,因为它会停下来告诉你发生了什么。