Click here to Skip to main content
15,888,088 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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>-

C
#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;
}
Posted
Updated 19-Sep-17 21:58pm
v2

Quote:
z=(-1)*k;

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

When k is odd you get z = -1 and eventually you access A[-1]
 
Share this answer
 
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).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900