c - 我在执行代码时收到段错误。有什么问题吗?

标签 c segmentation-fault

我正在学习 C 编程并尝试编写计算代码。当我的程序运行时,我遇到段错误。

问题出在哪里?

#include<stdio.h>
#include<string.h>

int main()
{   
    int n,i,j,k; 
    int c,x[10];
    printf("Enter the number of springs ");                                 
    scanf("%d",&n);

    int f[n],s[n],A[n][n+1][n+2]; //declare my variables here

    memset(A, 0, n*n+1*n+2*(sizeof(A))); //put all to zeros

    //store datas for stiffness and strength

    for(i=1;i<=n;i++)
    { 
        printf("Enter the stiffness of spring %d\n",i);                 
        scanf("%d",&s[i]);
    }

    for(i=1;i<=n;i++)
    {
        printf("Enter the force applied to the spring %d\n",i); 
        scanf("%d",&f[i]);
    }

    for(i=1;i<=n;i++){
        printf("\nforce applied in f[i] = %d",f[i]);
    }


    //computation for element 1 matrix

    for(k=1;k<=n;k++)

    for(i=1;i<=n+1;i++)

    {
        for(j=1;j<=n+2;j++)
        { 
            if(j==k||j==(k+1))
               A[k][i][j]=s[j];

            if(j==n+3)
                A[k][i][j]=f[j];
        }  
    } 

    for(k=1;k<=n;k++)
    {
        printf("\nmy n=%d matrix is\n",k);

        for(i=1;i<=(n+1);i++)
        {
            for(j=1;j<=(n+2); j++)
                printf("%d\t", A[k][i][j]);

                printf("\n");
        }
     }

     return 0;
}

最佳答案

更改memset(A,0,n*n+1*n+2*(sizeof(A)));

memset( A,0,n*(n+1)*(n+2)*sizeof(int)); 

还有for循环初始化应该是 i=0;和状况i<n .

关于c - 我在执行代码时收到段错误。有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478912/

相关文章:

c - Valgrind:无效读取和使用未初始化值

c - IDE 项目的源文件夹(Netbeans、Eclipse...)

c++ - 将代码从 C++ 转换为 C : `a+b > b+a` where a and b are `string`

c - 结构中的指针中不允许使用 VLA 有充分的理由吗?

c - 为什么这个取消引用内存别名区域的 C 程序会导致段错误?

c - 为什么 "mov %%rsp, %%rbp"导致段错误?

android - unity Android信号11(SIGSEGV),代码1(SEGV_MAPERR),故障地址0x0

c++ - 在C++中实现C-API文本 block 类时出错

c - 将 float 输入到仅处理整数的程序中

python - 在Python中读取大文件: Why am I getting a Segmentation Fault?