-1

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

  • 1
    Does this answer your question? [Practical difference between using array and pointer offset notation](https://stackoverflow.com/questions/58160944/practical-difference-between-using-array-and-pointer-offset-notation) – cafce25 Dec 04 '22 at 11:53
  • it is hard to understand the question gven there – Jiden Singh Dec 04 '22 at 12:03

1 Answers1

0

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.

Sterls
  • 723
  • 12
  • 22
  • No i mean difference between using *p=10 and p[0]=10 or *(p+1)=20 and p[1]=20 – Jiden Singh Dec 04 '22 at 11:52
  • But then does it also means then when i use malloc the array allocated to the process will have the same name as the pointer used to point the base address – Jiden Singh Dec 04 '22 at 11:56
  • *p=10 and p[0]=10 is the same thing. It just looks different. When you use malloc you're allocating memory that can hold a set amount of things. It allocates an array, yes, but it's more like a block of memory starting at p. p is just the variable used to represent the base address. – Sterls Dec 04 '22 at 12:00
  • they are the same p lol – Sterls Dec 04 '22 at 12:01
  • One more thing ,does the name of an array represents the base address of the array and element array[2] as an example means 1000(assuming base address)+2*sizeof(data type) – Jiden Singh Dec 04 '22 at 12:15
  • A variable name is something you would use to represent some block of memory. For example int x = 4. x is used to represent the data at some memory location as an integer. The pointer or the base address of x is the location of that memory. Your example with array[2] is correct! – Sterls Dec 04 '22 at 13:19