CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: Different sizeof array when I insert it by myself

1. Junior Member
Join Date
Apr 2019
Posts
1

## Different sizeof array when I insert it by myself

I'm just struggling with winding numbers algorithm. I have a homework to write a program where I have to insert points by myself of polygon and points which I'm going to investigate.
Anyway, the problem is I get a different output of sizeof(polygon) when I insert it by myself (4) than it is written in code (48). I dunno why and I'm struggling with this problem. I would be very grateful if someone could help!

2. ## Re: Different sizeof array when I insert it by myself

Please post formatted code using code tags rather than a screen image.

I think you're asking why the values of n1 and n2 in the code below are not the same?

Code:
```struct Point {
int x;
int y;
};

int main()
{
Point polygon1[] = { {2,2}, {4,4}, {6,6}, {-3,1}, {-1,-1}, {5,1} };

const size_t n1 = sizeof(polygon1) / sizeof(polygon1[0]);

cout << "n1 = " << n1 << endl;

Point* polygon2 = new Point[6];

for (size_t i = 0; i < 6; ++i)
cin >> polygon2[i].x >> polygon2[i].y;

const size_t n2 = sizeof(polygon2) / sizeof(polygon2[0]);

cout << "n2 = " << n2 << endl;
}```
giving
Code:
```n1 = 6
1 1 2 2 3 3 4 4 5 5 6 6
n2 = 0```
n1 is the expected value of 6.

However n2 is 0. The reason for this is that sizeof(polygon2) gives the size of the pointer - not the size of the memory to which polygon2 points. For a 32-bit compile, the size of a pointer is 32 bits (4 bytes) - so you get 4 / 8 which is 0.

Rather than using dynamically allocated memory, it would be better to use a vector if you don't know at compile time the size of the array.

Consider:

Code:
```struct Point {
int x;
int y;

Point(int x1, int y1) : x(x1), y(y1) {}
};

...

vector<Point> polygon3;

for (size_t i = 0; i < 6; ++i) {
int x, y;
cin >> x >> y;
polygon3.emplace_back(x, y);
}

cout << "n3 = " << polygon3.size() << endl;```
This gives the output:

Code:
```1 1 2 2 3 3 4 4 5 5 6 6
n3 = 6```
Last edited by 2kaud; April 22nd, 2019 at 05:52 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•