I am writing a program which will delete the repeated numbers in array. Passed the array through a function using pointer

30 Views Asked by At

This is the function that will delete the repeated numbers:

#include<stdio.h>
#include<conio.h>
int del(int *,int);
void main(){
    int s[5], i=0;
    clrscr();
    printf("Enter: ");
    for(i=0;i<5;i++)
        scanf("%d",s[i]);
    del(&s[0],5);
    for(i=0;i<5;i++)
        printf("%d",s[i]);
    getch();    
}

I think it has some error, I am not getting any error in the compiler, but the output is all "0".

int del(int *s, int n)

{
int i = 0,j=0;
for(i=0;i<n;i++)
 {
 for(j=0;j<n;j++)
     {
     if(*(s+i)==*(s+j))
          {
          *(s+j) = 0;
          }
     }
 }
return s;
}

1

There are 1 best solutions below

0
Alon Barenboim On

You have a few problems with your code.

First of all, when you use scanf you should give it a pointer, not a variable, so you need to add the '&' symbol before your variable name, so it will send an address to it.

scanf("%d",&s[i]);

Second of all, when you iterate through your array of integers, you use Nested loops, and it's great, but you start by comparing *(s+0) to *(s+0), since 'i' and 'j' are both initialized to be zero's.

So the second fix will be set 'j' to be 'i+1', not 0:

int del(int *s, int n)

{
int i = 0,j=0;
for(i=0;i<n;i++)
 {
 for(j=i+1;j<n;j++)
     {
     if(*(s+i)==*(s+j))
          {
          *(s+j) = 0;
          }
     }
 }
return *s; //(return an integer, not a pointer)
}

Now you'll always compare different placed numbers from your array.

Third thing and final: Your 'del' function should return integer (that's how you declared it) but you return 's' at the end, and it's int* (a pointer to integer). return *s instead.