請通過下面的循環:添加指針
我對第一循環特別迷茫,
第一環:
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; 對不起,我沒有進入整個程序 –