我正在尝试使用指针在 C 中计算 HCF。
int-type-Pointer ptr 指向一个整数数组。 我给出的输入是 30,60,18,a。这里的“a”是终止整数列表并中断“while”。
我尝试了 Debug模式,并找到了值:
*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 个整数内存。我只想在没有任何分配的情况下疯狂地使用指针。我知道它的不良做法,但我只想应用它。这对其他程序有什么危害吗?怎么办?
最佳答案
它是垃圾,因为您从未向它写入任何内容。看这段代码
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 (input==1 && scanf("%d", ptr)) // the first number is stored in smallest
{smallest = *ptr; continue;}
注意你如何continue
这里什么时候input
等于1
?这意味着 while
loop 将跳过所有其他内容并从头开始,它要做的第一件事是递增 input
。来自 1
至 2
.
关于c - 在第二个索引上获取一些垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126827/