zb22
zb22

Reputation: 3231

Allocation isn't working properly

I'm trying to put values in an array by sending the pointer address to a function and create dynamic allocation in the function itself. after the allocation, I get the first value in the first index.

This is the error message that for the problem: Unhandled exception at 0x00941589 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.

This is what I have done:

void mamain()
{
    *A = NULL;
    func(&A);
}


void func(int** A)
{
  *A = (int*)malloc(sizeof(int) * 5);

  *A[0] = 5;
  *A[1] = 8;
  *A[2] = 67;
  *A[3] = 2;
  *A[4] = 3;

   for (int i = 0; i < 5; i++)
   {
       printf("%d,", *A[i]);
   }
}

I don't understand why my code isn't working, trying to figure it out but no success.

Upvotes: 0

Views: 68

Answers (1)

John Bode
John Bode

Reputation: 123568

You've assigned the result of your malloc call to *A, not A; thus, the expression *A is your array. Since [] has higher precedence than unary *, the expression *A[0] is parsed as *(A[0]); this isn't what you want.

You'll need to explicitly group the * operator with A before doing the subscript:

(*A)[0] = 5;
(*A)[1] = 8;
...

Upvotes: 3

Related Questions