请通过下面的循环:添加指针
我对第一循环特别迷茫,
第一环:
for(i = 0; i < n; i++)
{
scanf("%d", ptr + i);
}
for(i = 0; i < n; i++)
{
sum = sum + (*(ptr + i));
}
第二环:
int *x ;
for(i = 0; i < n; i++)
{
x = ptr + sizeof(i);
scanf("%d",x);
}
for(i = 0; i < n; i++)
{
x = ptr + sizeof(i) ;
sum = sum + (*x);
}
为什么使用malloc 使用上述循环输入数组中的元素g同样的结果? 为什么第一个和第二个循环给出相等或正确的结果?
为什么(ptr + i)和ptr + sizeof(i)在相同的waY中工作?
整个程序
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
int main()
{
int *ptr;
int i, n, sum = 0 ;
float avg ;
printf("Enter the number of elements you want to store in the array.");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int)) ; /*Dynamic Memory allocation*/
if(ptr == NULL)
{
printf("The required amount of memory is not available. ");
getch();
exit(0);
}
else
{
printf("Enter the elements\n");
for(i = 0; i < n; i++)
{
scanf("%d", ptr + i);
}
for(i = 0; i < n; i++)
{
sum = sum + (*(ptr + i));
}
printf("\nThe sum of %d elements entered is = %d",n , sum);
avg = sum/n ;
printf("\nThe average of %d number of the array is %f", n, avg);
}
printf("\n");
getch();
}
如何声明'ptr'? – lurker
'x'被声明为'int',并且您试图对其进行解引用。 – mathematician1975
int * x; 对不起,我没有进入整个程序 –