如何使用malloc在ANSI-C中声明动态整数数组并将输入整数放入其中? [英] How to declare a dynamic integer array in ANSI - C using malloc and put input integers into it?

查看:145
本文介绍了如何使用malloc在ANSI-C中声明动态整数数组并将输入整数放入其中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

First I want the user to input what is the size of the desired array. So I am using:

int size;
scanf("&d",&size);

现在,我想使用指针和malloc函数创建一个整数数组. 这就是我所做的:

Now I want to create an integer array using a pointer and the malloc function. This is what I did:

int *p1 = (int*)malloc(sizeof(int)*size);

据我了解,这就像使用:

According to my understanding, this is like using:

int p1[size];

但是我如何像数组一样使用它?

But how do I use it like an array?

问题:1: 现在,我希望用户输入与他写入此数组"一样多的整数. 但是我不能使用p [0],因为它不是数组,而是指针.

Question 1: Now I want the user to input as many integers as he wrote into this "array". But I can't use p[0] because it is not an array, it is a pointer.

问题 2: 我想将此数组发送"到一个获取整数数组的函数. 再说一遍,这不是数组,如何将其提供"给函数?

Question 2: I want to "send" this array to a function that gets an array of integers. So again, this is not an array, how can I "give" it to the function?

推荐答案

第一个问题的答案:

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
}

第二个问题的答案:

要将此数组发送给函数,只需像下面这样调用函数:

For sending this array to the function, just call the function like this:

function(p); //this is sending the address of first index of p

void function( int *p ) //prototype of the function

这篇关于如何使用malloc在ANSI-C中声明动态整数数组并将输入整数放入其中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆