Pepperwork
Pepperwork

Reputation: 105

c++: what is int[3] in sizeof(int[3])

This is my example:

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    int ar[][3] = {1, 2, 3, 4, 5, 6, 7};
    //cout << int[3]<<endl; // error C2062: type 'int' unexpected.
    cout << "sizeof(ar) / sizeof(int[3])  "<< sizeof(ar) / sizeof(int[3]) << endl;; 

    system("pause");

    return 0;
}

It is from a book, though no explanation was given. What is int[3] here and why it works only as an argument of sizeof in this case?

Upvotes: 1

Views: 2557

Answers (3)

emsr
emsr

Reputation: 16333

The declaration

int ar[][3] = {1, 2, 3, 4, 5, 6, 7};

is for an array of triplets of integers - it is a 2D array.

The sizeof expression

cout << "sizeof(ar) / sizeof(int[3])  "<< sizeof(ar) / sizeof(int[3]) << endl;

prints the number of full triplets that you get. The last integer, 7, will not fall into any triplet. You should see 2 printed. ar[0] will contain {1, 2, 3} and ar[1] will contain {4, 5, 6}.

Upvotes: 2

Matt Kline
Matt Kline

Reputation: 10477

sizeof(int[3]) is the size, in bytes, of an array of three integers. sizeof isn't an actual function that gets called while your program is running - it is resolved at compile time. sizeof(ar) / sizeof(int[3]) will give you the number of rows in your array, since each row is 3 integers long (you declared it as int ar[][3]).

Upvotes: 2

SLaks
SLaks

Reputation: 887225

int[3] is a type declaration that represents an array of three integers.

Your commented code gives an error because you can't use a type as a variable.

Upvotes: 3

Related Questions