0

When the 1st value I've assigned to the integer "number" gets assigned to the R array, my program crashes. It probably has something to do with the pointer I've created and I do not seem to be able to find what is the problem. If I omit this part of the code:

else{ while (k<=n/2){ temp2=R[k]; R[l-1]=temp2; R[k]=R[l-1];} l-=1; k+=1; } 

, the program runs fine, even though it gives a different output. Below is the code:

#include <stdio.h> main(){ int i,n,number,temp,j,k=0,l,temp2; int *R; R=(int *)malloc(n*sizeof(int)); printf("Dwse mou to megethos tou pinaka se parakalw poly:\n"); scanf("%d", &n); for(i=0; i<n; i++){ printf("Dwse enan thetiko akeraio arithmo:\n"); scanf("%d", &number); R[i]=number; } for(i=1;i<n;i++){ temp=R[i]; j=i-1; while((temp>R[j])&&(j>=0)){ R[j+1]=R[j]; j=j-1; } R[j+1]=temp; } l=n; if (n%2==0) printf("Einai adynato na ginei h taksinomhsh:\n"); else{ while (k<=n/2){ temp2=R[k]; R[l-1]=temp2; R[k]=R[l-1];} l-=1; k+=1; } for(i=0; i<n; i++){ printf("R[%d]: %d\n", i, R[i]); } } 

Thank you.

7
  • 1
    R=(int *)malloc(n*sizeof(int)); move to after scanf("%d", &n);. Commented Dec 30, 2016 at 18:06
  • 1
    you are allocating the array R using the variable n which is not initialized Commented Dec 30, 2016 at 18:07
  • Well, thank you very much and pardon me for making such kind of questions due to my noobishness. Commented Dec 30, 2016 at 18:11
  • Also else-block is wrong. Commented Dec 30, 2016 at 18:16
  • What's not right? Commented Dec 30, 2016 at 18:19

1 Answer 1

2
int i,n,number,temp,j,k=0,l,temp2; int *R; R=(int *)malloc(n*sizeof(int)); 

What value does n have? It's uninitialized, so you invoke undefined behavior in C lingo. Anything may happen, and a crash is one thing.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That was the problem indeed.
@Achilles Wonderful. The next step on Stack Overflow is to accept the answer that helped you most by clicking the green check mark to the left. This will earn you a few points of credit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.