Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign values in an array of arrays properly?

Is there a way to assign values in an array of arrays?

Specifically, I have written the following code:

#include <stdio.h>
#include <stdlib.h>

void func(int **A){  //A: address of (address of pointer)
  int i;
  *A=(int *)malloc(5*sizeof(int));    //*A: address of pointer
  for (i=0;i<5;i++){
    **A=i;          //**A: content
  }
}

int main(){
  int *k, i;
  func(&k);

  for (i=0;i<5;i++){
    printf("%d ", k[i]); 
  }
  return 0;
}

The statement **A=i inside the function, seems to assign the values only in the first place of the array (the output is 4 0 0 0 each time I execute the code).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have also tried using *A[i]=i instead. In this case, the compiler terminates the execution with the following message: signal: illegal instruction (core dumped) .

Is there anything I could do to solve this?

>Solution :

The array index operator [] has higher precedence than the dereference operator *.

You’ll need to use parenthesis do what you want.

(*A)[i]=i; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading