分段错误,错误答案 [英] Segmantation fault, wrong answer

查看:139
本文介绍了分段错误,错误答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是segmantation错误...并告诉我为什么我的程序显示Hackerrank中的segmantation错误。



我尝试过:



问题> -

给定一个N数组。按用户指定的方向(左或右)旋转数组的元素。如果旋转指数为负,则向左旋转否则向右旋转



输入格式



输入将包含2行。

第一行包含2个整数,指定元素数和旋转索引。

第二行包含数组的空格分隔元素。



限制条件



N> = 1



输出格式



数组的空格分隔元素



样本输入0



7 -2

1 2 3 4 5 6 7

样品输出0



3 4 5 6 7 1 2

说明0



-2表示左旋2次。

所以1 ,2到阵列的后面



答案> -



I want to know what is segmantation fault...And tell me why my programme shows segmantation fault in Hackerrank.

What I have tried:

Question>-
Given an N numbers array. Rotate the elements of the array in the direction specified by the user(Left or right). If rotation index is Negative, rotate Left otherwise rotate Right

Input Format

Input will contain 2 lines.
First line contains the 2 integers specifying number of elements and the rotation index.
Second line contains space separated elements of the array.

Constraints

N >= 1

Output Format

Space separated elements of the array

Sample Input 0

7 -2
1 2 3 4 5 6 7
Sample Output 0

3 4 5 6 7 1 2
Explanation 0

-2 means 2 left rotations.
So 1, 2 goes to the back of the array

Answer>-

#include <stdio.h>
//#include<string.h>
int main()
{
    int i,j,n,k,z;
    int o=0;
    int A[99999],B[99999];
    scanf("%d%d",&n,&k);
    //int *A=malloc(sizeof(int)*n);
    //int *B=malloc(sizeof(int)*n);
    for(i=0; i<n; i++)
        scanf("%d",&A[i]);
if(k<0)
{
     z=(-1)*k;

    for(i=z; i<n; i++)
        B[o++]=A[i];
    for(i=0; i<z-1; i++)
        B[o++]=A[i];
    for(i=z-1; i<z; i++)
        B[o++]=A[i];
    //free(A);
        
    }
    else if(k>0)
    {
    for(j=n-k; j<n; j++)
        B[o++]=A[j];
    for(j=0; j<n-k-1; j++)
        B[o++]=A[j];
    for(j=n-k-1; j<n-k; j++)
        B[o++]=A[j];
       // free(A);
    }
    for(i=0; i<n; i++)
        printf("%d ",B[i]);
    return 0;
}

推荐答案

Quote:

z =( - 1)* k;



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

B [o ++] = A [i];

z=(-1)*k;

for(i=z; i<n; i++)
B[o++]=A[i];



k 为奇数时,你得到 z = -1 并最终访问 A [-1]


When k is odd you get z = -1 and eventually you access A[-1]


参见分段错误 - 维基百科 [ ^ ]。



为什么在HackerRank检查时你的代码出现在这里无法回答,因为我们不知道它是如何在那里执行的。



但可能是他们的测试包括传递程序无法处理的无效输入值(例如n< 1,n> = 99999,abs(k) )> n)。
See Segmentation fault - Wikipedia[^].

Why it occurs with your code when checked at HackerRank can't be answered here because we don't know how it is executed there.

But it might be that their tests include passing invalid input values which are not handled by your program (e.g. n < 1, n >= 99999, abs(k) > n).


这篇关于分段错误,错误答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆