Search code examples
cmemorydynamicindirection

I am getting error in this code as "invalid indirection"


I am trying to dynamically allocate a contiguous block of memory, store some integer value and display it.

#include<stdio.h>
#include<conio.h>
void main()
{     int i;
      int *ptr;
      ptr=(void *)malloc(sizeof(int)*5); //allocation of memory

      for(i=0;i<5;i++)
              {     scanf("%d",&ptr[i]);
              }    
      for(i=0;i<5;i++)
              {    printf("%d",*ptr[i]); //error is found here``                     
              }
}    }

Solution

  • ptr[i] means the value at address (ptr+i) so *ptr[i] is meaningless.You should remove the *

    Your corrected code should be :

     #include<stdio.h>
     #include<stdlib.h>
     #include<conio.h>
     int main()
     { 
      int i;
      int *ptr;
      ptr=malloc(sizeof(int)*5); //allocation of memory
    
      for(i=0;i<5;i++)
              {     scanf("%d",&ptr[i]);    
               }    
      for(i=0;i<5;i++)
              {    printf("%d",ptr[i]); //loose the *
              }
      return 0;
    }     //loose extra }