I'm trying to calculate HCF in C with pointers.
int-type-Pointer ptr points to an array of integers. The inputs that i have given are 30,60,18,a. And here "a" is to terminate the list of integers and breaks off the "while".
I tried the debug mode, and found the values:
*ptr = 30
*(ptr+1)= -1163005939 //the garbage that i'm talking of.
*(ptr+2)= 60
*(ptr+3)= 30
while what i should get are 30, 60,18.
#include<stdio.h>
void main(){
int* ptr=(int*) malloc( sizeof(int)* 50);
int input=0;
int smallest;
printf ("Enter the numbers (press any alphabet when you're done )\n");
while (1)
{ input++;
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
if (!scanf("%d",ptr+input )) // if the input is a character , scanf says 0,
{input--; //! makes it 1, and we jump out of the loop
break;}
if (smallest > *(ptr+input)) // swapping
{ smallest += *(ptr+input);
*(ptr+input) = smallest- *(ptr+input);
smallest= smallest- *(ptr+input);
}
}
// code for determining the HCF
char c;
if (smallest <=0)
{
printf("", scanf("%c",&c ), printf("Answer is 0")); // it will print that the answer
exit(0); //is 0 then waits for you to
} //press any key and then it exits
//if smallest greater than 0
int i=2;
int HCF=1;
int j;
for (; i<smallest/2; i++)
{ for (j=0; j<=input;j++)
// this is where the problem is suspected
//as i ve seen in the debug mode
//it gives results divides the garbage value to i
{if (! (*(ptr+j)%i == 0)) // if the number stored in the location is not
break; //divisible by i, then leave that number i
} //and check for the next i
if (j>input)
HCF *= i;
}
printf( "", scanf("%c", c), printf("The HCF is %d ", HCF));
free(ptr);
}
So what is the problem? And i didnt want to allocate the 50 ints memory. I wanted to just use the pointer wildly without any allocation. I know its bad practice but i just want to apply it . Is that any harm to other programs? How?
It's garbage because you never write anything to it. Look at this code
while (1)
{ input++;
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
if (!scanf("%d",ptr+input )) // if the input is a character , scanf says 0,
{input--; //! makes it 1, and we jump out of the loop
break;}
//code that doesn't assign values to ptr
}
by the time you get to scanf("%d",ptr+input )
, input
will be 2
if scanf("%d", ptr)
returned a truthy value. That's because of this if statement:
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
notice how you continue
here when input
is equal to 1
? that means that the while
loop will skip everything else and begin again from the beginning, and the first thing that it's going to do is increment input
from 1
to 2
.