Traversing an array using malloc

1

In the course of some questions here in the OS I saw this example and I had doubts.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

void main()
{
clrscr();
int *ptr,*temp;
int i;

ptr = (int *)malloc(4*sizeof(int));
temp = ptr;  

for(i=0;i < 4;i++)
     {
     printf("Enter the Number %d : ",i);
     scanf("%d",ptr);
     ptr++;         
     }

ptr = temp;
   for(i=0;i < 4;i++)
   {
   printf("\nNumber(%d) : %d",i,*ptr);
   ptr++;
   }

getch();
}

What is really happening in this example?

Why do you use ptr++ and not ptr[x] ?

Does malloc not always allocate continuous memory?

    
asked by anonymous 15.02.2018 / 18:27

1 answer

2
  

What is really happening in this example?

For all effects you are accessing an array , although technically the definition is a bit different a>. In C the array is always accessed through pointers.

  

Why do you use ptr ++ and not ptr [x]?

Because whoever made the code wanted it that way. Both work. It is common to use pointer notation when using pointer and array notation when using array . ptr[x] is only syntactic sugar for *(ptr + x) . The pointer shape is changing the pointing location so you had to create a temporary variable to hold the original value of the beginning of the array . usually if you need a temporary variable the ideal would be the array notation.

  

Is it possible to use this formula ptr [x]?

I do not know what that means.

  

Does malloc not always allocate continuous memory?

Yes, one thing has nothing to do with another.

This code could be written like this:

#include<stdio.h>
#include<stdlib.h>

void main() {
    int *ptr = malloc(4 * sizeof(int));
    int *temp = ptr;  
    for (int i = 0; i < 4; i++) {
         printf("\nEnter the Number %d : ", i);
         scanf("%d", temp++);
    }
    for (int i = 0; i < 4; i++) printf("\nNumber(%d) : %d", i, *ptr++);
}
    
15.02.2018 / 18:39