Traverse an array using malloc

Asked

Viewed 236 times

1

In the course of some questions here in the SO I saw this example and I was left with 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 wear ptr++ and not ptr[x]?

malloc does not always allocate continuous memory?

1 answer

2


What is really happening in this example?

For all intents and purposes you are accessing a array, albeit technically the definition is a little different. In C the array is always accessed via pointers.

Why is ptr++ used and not ptr[x]?

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

It is possible to use this formula ptr[x]?

I don’t know what that means.

malloc does not always allocate continuous memory?

Yes, one has nothing to do with the other.

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++);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.