我正在尝试用指针计算C中的HCF。
int-type-Pointer ptr指向一个整数数组。 我给出的输入是30,60,18,a。这里“a”是终止整数列表并中断“while”。
我尝试了调试模式,找到了值:
*ptr = 30
*(ptr+1)= -1163005939 //the garbage that i'm talking of.
*(ptr+2)= 60
*(ptr+3)= 30
虽然我应该得到的是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);
}
那么问题是什么? 而且我不想分配50个内存。我想在没有任何分配的情况下疯狂地使用指针。我知道它的不良做法,但我只是想应用它。这对其他程序有害吗?怎么样?
答案 0 :(得分:2)
它是垃圾,因为你从不写任何东西。看看这段代码
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
}
当您到达scanf("%d",ptr+input )
时,如果input
返回真值,则2
将scanf("%d", ptr)
。这是因为if if语句:
if (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
当continue
等于input
时,请注意1
在这里的方式?这意味着while
循环将跳过其他所有内容并从头开始重新开始,而它要做的第一件事就是将input
从1
增加到{{ 1}}。