-1

In the program below, inside the main function, while entering elements in an array it runs one more time and also the insertion function is inserting random values.
I think I am doing a mistake in the insertion function. Here I want to first shift the elements and then I want to insert when it found an element smaller than that I want to insert.

#include<stdio.h>
#include<stdlib.h>
struct Array
{
    int *A;
    int length;
    int size;
} p;
        
void Display(struct Array p)
{
    int i;
    for(i=0;i<p.length;i++)
    {
        printf(" %d ",p.A[i]);
    }
}
       
// I think I am doing a mistake in the insertion function below. Here I want to first shift the elements and then I want to insert when it found an element smaller than that I want to insert.

void inserting(struct Array *p,int x)
{
    int i=p->length-1;
    if(p->length=p->size)
    {
        return;
    }
    while(i>=0 && p->A[i]>x)
    {
        p->A[i+1]=p->A[i];
        i--;
    }
    p->A[i+1]=x;
    p->length++;    
}
    
    
int main()
{
    int i,ch,index,el,choice=1,c;
    printf("Enter size of array\n");
    scanf("%d",&p.size);
    p.A=(int *)malloc(p.size * sizeof(int));
    printf("Enter length of Array\n");
    scanf("%d",&p.length);
    printf("ENTER elements in an array\n");
    for(i=0;i<p.length;i++)
    {
        scanf("%d\n",&p.A[i]);
    }
    // The above loop takes input one more time than expected.
    inserting(&p,20);
    Display(p);
    return 0;
}
Dada
  • 6,313
  • 7
  • 24
  • 43
  • For the first problem: `scanf("%d\n",&p.A[i]);` -> `scanf("%d",&p.A[i]);`. See: [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) – kaylum Jul 03 '21 at 05:23
  • Next problem: `if(p->length=p->size)` --> `if(p->length==p->size)` – kaylum Jul 03 '21 at 05:25
  • If you are using `gcc` or `clang`, you should pretty much always compile with the flags `-Wall` and `-Wextra`. They enable a lot of warnings, which should help you catch a lot of errors early. – Dada Jul 03 '21 at 12:28

1 Answers1

2
        if(p->length=p->size)

Assignment in a conditional, a decent compiler I think would warn for this.

Richard Rowell
  • 318
  • 1
  • 8