0

I have a project where I have to realize a function that takes as parameter a pointer of pointer (**). This variable contains a "2D array" of [N_ROW][N_COL].

PS : [N_ROW][N_COL] are very big and my compiler generated an error that I have to declare the variable in the heap memory and not in the stack so I guess I have to use malloc.

My problem is that to realize/test this function, I have to create myself this variable with the data inside. The notion of double pointer is completely new to me and I get mixed up between a simple variable and an array whose index is already an address. I read on the forums that a double pointer for a 2D array is useless. That a 2D array is not a double pointer. I am too confused...

What should I do to initialize a table that would be a double pointer to pass as input to my function? And I have no choice, the function I have to create must take a double pointer. Prototype exemple :

void myFunction (float **myTable);

EDIT : Here my code to try...

#define NB_COL            100
#define NB_ROW          5


void myFunction (float **myArray)
{
  int i=0;
  int j=0;

  /* Write */
  for (i = 0; i < NB_ROW; i++)
  {
    for (j = 0; j < NB_COL; j++)
    {
      myArray[i][j] = i*NB_ROW+j;
    }
  }


  /* Read */
  for (i = 0; i < NB_ROW; i++)
  {
    for (j = 0; j < NB_COL; j++)
    {
      printf("%f", myArray[i][j]);
    }
    printf("\n");
  }

}

int main(void)
{
  /* Init variables */
  float (*myArray)[NB_ROW][NB_COL];

  /* Allocate a 2D array */
  myArray = malloc(sizeof(float[NB_ROW][NB_COL])); 
  assert(myArray != NULL);

  /* My funtion */
  myFunction(myArray);


  free(myArray);

  return 0;
}

I initialized my array correctly but I have a "segmentation fault". I don't understand how I use my variables -_-

CousCous
  • 31
  • 6
  • It's correct that you shouldn't allocate huge arrays on the stack, but where you allocate the array has nothing to do with how you pass it to a function. – Lundin Feb 02 '22 at 14:56
  • @AlexF That link only contains C90 stone age "mangled arrays" like we programmed in the 1990s. In general, I wouldn't recommend reading tutorialspoint for any purpose since the page has a very poor reputation. – Lundin Feb 02 '22 at 14:57
  • @Lundin You *could* close against the canonical I linked. (I seem to recall that you don't like doing that when the target is your own, but I have already placed one CV for it.) – Adrian Mole Feb 02 '22 at 15:15
  • @AdrianMole I avoid doing that when I'm partial indeed. Especially since it would then get "dupe hammered". – Lundin Feb 02 '22 at 15:24
  • I updated my post... I still don't understand why I can't use my "table" :/ – CousCous Feb 02 '22 at 15:45

0 Answers0