问题描述
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p, n, i;
printf("Enter the size of the array:");
scanf("%d", &n);
p = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{
printf("\n Enter element %d:", i + 1);
scanf("%d", &p[i]);
}
for (i = 0; i < n; i++)
printf("\n %d", p[i]);
return 0;
}
为什么我们需要写&安培;
在scanf函数,如果它是没有必要的数组? P
是指向所有内存空间让&安培; P [I]
应该给指针的地址,但不是我们要存储的数据吗?
此外,如果我们写 * P [I]
在的printf
,它给出了一个错误,点
是一个指针,所以我们要尊重它,并把数据存储在内存中的保留空间,但它不工作?即使我编译上面的程序,因为它是停止服用3个值作为输入工作后。
Why do we need to write &
in the scanf, if it's an array it's not necessary?p
is a pointer to all the memory spaces so &p[i]
should give the address of the pointer but not where we want to store the data right?Also if we write *p[i]
in printf
, it gives an error, p
is a pointer so we should deference it and store the data in the reserved space in the memory but it's not working? Even if I compile the above program as it is it stops working after taking 3 values as input.
推荐答案
下标运算符[]也进行提领。这一次进行索引和非关联化。 P [N]
等同于 *(P + N)
,即它去偏移和间接引用它。因此,&安培; P [N]
等同于点+ N
The subscript operator [] also performs dereferencing. It performs indexing and dereferencing at once. p[n]
is equivalent to *(p+n)
, i.e. it goes to an offset and dereferences it. Consequently, &p[n]
is equivalent to p+n
.
这篇关于Ç内存分配(malloc的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!