c++arrayspointers

C++ array pointer to pointer


// Declaring a variable:
int* buf = new int[max_size];

// Filling in the data:
for (int i = 0; i < max_size; ++i) buf[i] += i;

// We pass it to the function:
process(&buf);

Implementation function:

void process(const int* const* buf)
{
  int a = 0;
  int ch = 1;
  for(int c = 0; c < ch; ++c)
    for (int i = 0; i < max_size; ++i)
      a += buf[c][i]; // ???
}

How and by what rule is my array masquerading as an array of arrays? a += buf[c][i];

Try here: https://www.programiz.com/online-compiler/2VrwQHT2IG5pE

P S: I think this is because here &but we pass the address for the const float* const* buf part. But maybe there is a more academic explanation for this?


Solution

  • If you're asking why a += buf[c][i]; works, that's because buf is a pointer to the pointer of the first element of the array.

    Since the for loop of c only runs for 0 <= c < 1. This line is essentially

    a += buf[0][i];
    

    Which is

    a += (*buf)[i];
    

    (FYI, in general ptr[i] == *(ptr+i))

    i.e you dereference buf to get the pointer to the array, and then dereference the i-th member of the array.

    This code has multiple problems

    // Declaring a variable:
    int* buf = new int[max_size];
    

    Here you should probably use std::array<int, max_size> in C++, if max_size is a compile-time constant. Otherwise std::vector<int>(max_size) is a good choice, this way you don't have to manually manage the memory.

    // Filling in the data:
    for (int i = 0; i < max_size; ++i) buf[i] += i;
    

    Here, you assume that your array is set to 0 at each element, this is wrong, you should initialize it.

    // We pass it to the function:
    process(&buf);
    

    Here, there's no reason to pass a pointer to buf as buf is already a pointer.

    Your process function should be something like this.

    void process(const int* buf)
    {
      int a = 0;
      for (int i = 0; i < max_size; ++i)
        a += buf[i];
    }
    

    I recommend reading about C++ and discovering the languages features.