I'm a novice user of C language. I have a problem in allocating a dynamic array.
I used to allocate memory outside the loop such as a=(int*)malloc(5* sizeof(int));
and every thing worked fine. Now I want to allocate memory to each element one by one in a loop using malloc()
, but the code is not working.
I've tried different options like scanf("%d",a) &a++,scanf("%d",&a[i]);
etc but could not succeed. If anyone can tell me what I was doing wrong and explain to me the concept thoroughly, I'll be thankful.
The code which I'm having problems with is the following:
#include <stdio.h>
#include<stdlib.h>
int main()
{
int *a;
int i;
system("clear");
for(i=0;i<5; i++)
{
a=(int *)malloc(sizeof(int));
printf("%u",&a);
printf("please enter the element in array");
scanf("%d",a[i]);
}
for(i=0;i<5; i++)
{
printf("\nthe %d entry in the array %d",i,a[i]);
}
return 0;
}