Here is a code for dynamic memory allocation using malloc
void main()
{
int *p,n=5;
p=(int*)malloc(5*sizeof(int));
p[0]=10;
// or *p=10;
p[1]=20
// or *(p 1)=20;
}
As per my knowledge, p
is a pointer variable that points to the base address of the allocated memory. If I dont use the *
operator, then I can't access the contents pointed to by p
. But the statements p[1]=20
and *(p 1)=20
do work the same. Why is this same and also what is the use of *
if we can do it this way too p[1]
But then does it also means that when i use malloc the array allocated to the process will have the same name as the pointer used to point the base address
CodePudding user response:
The difference between *p and p[1] is that *p is a pointer that points to the first element of the array, while p[1] is the second element of the array. The difference is that *p gives you access to the entire array, while p[1] only gives you access to the single element.