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

1.8k views Asked by At

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``                     
              }
}    }
1

There are 1 answers

2
Sourav Kanta On BEST ANSWER

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 }