【问题标题】:Segmentation fault in array数组中的分段错误
【发布时间】:2022-12-03 08:58:08
【问题描述】:

尝试通过数组从用户获取行数和列数,但在运行时会出现分段错误

#include<stdio.h>
int main(){
    int rows;
    int column;
    int arr[rows];
    int arr1[column];
    
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    printf("Enter the number of column: ");
    scanf("%d",&column);
    printf("\n");
    
int i=0;
while( i<rows)
{  printf("\n");
   printf("Enter the value of rows index: " );
   scanf("%d",&arr[i]);
   printf("\n");
    i++;
}
int j=0;
while(j<column)
{
   printf("Enter the value of rows index: " );
   scanf("%d",&arr1[j]);
   printf("\n");
    j++;
}
}

// giving Segmentation fault

【问题讨论】:

    标签: arrays c loops segmentation-fault fault


    【解决方案1】:

    该程序出现分段错误,因为数组“arr”和“arr1”是在获取用户输入之前声明的。两个数组的大小必须在使用前设置。

    为了解决这个问题,我们需要在获取用户输入后声明数组。

    #include<stdio.h>
    int main(){
        int rows;
        int column;
        
        printf("Enter the number of rows: ");
        scanf("%d",&rows);
        printf("Enter the number of column: ");
        scanf("%d",&column);
        printf("
    ");
        
        int arr[rows];
        int arr1[column];
        
    int i=0;
    while( i<rows)
    {  printf("
    ");
       printf("Enter the value of rows index: " );
       scanf("%d",&arr[i]);
       printf("
    ");
        i++;
    }
    int j=0;
    while(j<column)
    {
       printf("Enter the value of rows index: " );
       scanf("%d",&arr1[j]);
       printf("
    ");
        j++;
    }
    }
    

    【讨论】:

      【解决方案2】:

      在您定义“arr”和“arr1”数组时,列和行的值未定义。

      int rows;
      int column;
      int arr[rows];
      int arr1[column];
      

      在收到用户的输入后移动这些数组的声明。

      printf("Enter the number of rows: ");
      scanf("%d",&rows);
      printf("Enter the number of column: ");
      scanf("%d",&column);
      printf("
      ");
      int arr[rows];
      int arr1[column];
      

      试一试,看看是否能解决您的分段错误。

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 2017-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多