0
#include "stdafx.h"
#include<iostream>
#include<conio.h>
#include<ctime>
using namespace std;
int *p[10][20];//
int _tmain(int argc, _TCHAR* argv[])
{
    cout<<sizeof(*p)<<endl;
    getch();
    return 0;


}

output: 80
but  i cannot understand how it work.
4
Contributors
5
Replies
38
Views
3 Years
Discussion Span
Last Post by sepp2k
0

What don't you understand?

You are creating a pointer to an array and trying to output the size, this is not allowed sice the compiler does not know what the pointer is pointing to.

In your cose, you woud not not need a pointer, it would just work lik this:

#include<iostream>

using namespace std;
int p[10][20];//
int main()
{
    cout<<sizeof(p)/sizeof(int)<<endl;
    //getch();
    return 0;
} //output: 200
1

You are creating a pointer to an array

No, he's not. He's creating an array of arrays of pointers.

and trying to output the size, this is not allowed sice the compiler does not know what the pointer is pointing to.

Yes, it's allowed and yes, the compiler knows perfectly well what p (or rather the pointer that p decays to) is pointing to: to a 20 element arrays of int pointers. So it returns sizeof(int*) * 20

And if he had created a pointer to an array (by writing int (*p)[10][20] instead of int *p[10][20]), it'd still be allowed and the compiler would still know what p points to: a 10x20 array of int. So in that case it would return sizeof(int) * 200.

Votes + Comments
Nice!
0

I'm sorry, I do not understand your reply. I said that "in that case it [i.e. sizeof(*p)] would return sizeof(int) * 200". So yes, that's the same as sizeof(*p) (if p had been defined as a pointer to an array) - that's what I was saying.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.