TomG TomG - 3 years ago 63
C Question

How to declare a dynamic integer array in ANSI - C using malloc and put input integers into it?

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

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


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?

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.

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?

Answer Source

Answer to first question:

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 */
}

Or

for(i = 0; i < size; i++ )
{
   scanf("%d",(p+i)); //here p+i is the address of element at index i
}

Answer to second question:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download