首先,我希望用户输入所需数组的大小。 所以我正在使用:
int size;
scanf("&d",&size);
现在我想使用指针和 malloc 函数创建一个整数数组。 这就是我所做的:
int *p1 = (int*)malloc(sizeof(int)*size);
根据我的理解,这就像使用:
int p1[size];
但是如何像数组一样使用它呢?
问题 1: 现在我希望用户输入尽可能多的整数,因为他写入这个“数组”。 但是我不能使用 p[0],因为它不是一个数组,它是一个指针。
问题 2: 我想将这个数组“发送”到一个获取整数数组的函数。 所以,这又不是一个数组,我怎么能把它“给”给函数呢?
最佳答案
第一个问题的答案:
for(i = 0; i < size; i++ )
{
scanf("%d",&p[i]);
/*p[i] is the content of element at index i and &p[i] is the address of element
at index i */
}
或者
for(i = 0; i < size; i++ )
{
scanf("%d",(p+i)); //here p+i is the address of element at index i
}
第二个问题的答案:
要将这个数组发送给函数,只需像这样调用函数:
function(p); //this is sending the address of first index of p
void function( int *p ) //prototype of the function
关于c - 如何使用 malloc 在 ANSI - C 中声明动态整数数组并将输入整数放入其中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16035952/