-2

The memory address of each element of an array are displayed as

int first[4], n=4;
for(int i=0;i<n;i++){
   cout<<"first#" <<i<<" "<<&first[i]<<endl; 
}

I want to ask how to output the address of each element allocated using malloc?

int *first = (int *) calloc(n, sizeof(int));
sara
  • 71
  • 6

1 Answers1

0

Your code could be used exactly the same way to output the malloc allocated memory.

Or you could do the the pointer way like below :

int *array;
array=malloc(4*sizeof(int);
for(int i=0;i<4;i++)
  printf("Address %d : %p\n",i,(array+i));

What difference would you think it makes, if the memory is allocated automatically or manually(as in malloc)?

M.M
  • 138,810
  • 21
  • 208
  • 365
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • 1
    This answer on SO [link](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) indicates quite strongly that malloc should not be cast. array=malloc(4 * sizeof(int)); – anita2R Apr 13 '16 at 11:53
  • @anita2R OP apparently is using C++ but incorrectly tagged question, so malloc would need to be cast there. Also if you read that whole link then `malloc(4 * sizeof *array);` is the recommended form. Removing cast without also changing the `sizeof` makes the code worse by removing error-checking. – M.M Apr 14 '16 at 04:53
  • @M.M The line shown 'array=malloc(4*sizeof(int));` has been edited - it was originally (if I remember correctly) `array=(int *) malloc(4*sizeof(int));`, and yes - the OP's code in the question must be C++ ... although the answer (accepted) appears to be C - which is what I commented on. – anita2R Apr 14 '16 at 12:42