c - 如何使用 malloc 在 ANSI - C 中声明动态整数数组并将输入整数放入其中?

标签 c arrays pointers malloc ansi

首先,我希望用户输入所需数组的大小。 所以我正在使用:

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/

相关文章:

c - Valgrind 段错误无效写入大小 8 C

c++ - 编译器如何知道指针的类型

无法在内联汇编中声明 .data

c - Makefile 说明 : files that includes headers which includes another header

javascript - 将数组插入多维数组

javascript - 有没有办法在数组 x 上运行 .push() 方法? (在 for 循环之外)

c++ - 基于双向链表的双端队列实现不起作用

c++ - C++中的this->member VS member

c - main() 中的 GDB 断点无法访问内存

c - 在C中显示来自Web服务器的图像