Domanda

I've been battling with figuring out how to pass a 2D array to a function and I think I've figured it out. My problem now though is for some reason this array (see below) is growing from 25 to 100 and I can't figure out why. I can't pinpoint where it's going haywire.

#include <iostream>

void testFunc(int (&n)[5][5]) {
  n[0][0] = 5;
}

int main() {
  int arr3[5][5];
  // The array is initialized here with all values equaling 8.
  for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
      arr3[i][j] = 8;
    }
  }

  testFunc(arr3);     // Function is called here changing [0][0] to the value 5.
  for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
      std::cout << arr3[i][j] << ' ';
    }
    std::cout << '\n' << std::endl;
  }
  std::cout << sizeof(arr3) << std::endl;
  return 0;
}

When I try to write the for-loop with i < sizeof(arr3) I get a size of 100. Not sure why. Where is it getting that value?

È stato utile?

Soluzione

Your array size is 5*5 = 25, and int takes 4 bytes. so it becomes 100.

Altri suggerimenti

sizeofis not the number of elements. It's the size of the object in chars, that is, in bytes for most modern systems.

Your system has 32-bit (4 char/bytes) ints. Which gives you 5*5*4 = 100.

The size of data is also depend on size of CPU registers. In 32 bit machine the size of int is 4. However in earlier 16 bit machines the size of int is 2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top