Home > Backend Development > C++ > A C/C++ pointer puzzle?

A C/C++ pointer puzzle?

WBOY
Release: 2023-09-21 23:33:03
forward
1269 people have browsed it

A C/C++ pointer puzzle?

Suppose we have an integer variable whose size is 4 bytes and another pointer variable whose size is 8 bytes. So what will be the output below?

Example

#include<iostream>
using namespace std;
main() {
   int a[4][5][6];
   int x = 0;
   int* a1 = &x;
   int** a2 = &a1;
   int*** a3 = &a2;
   cout << sizeof(a) << " " << sizeof(a1) << " " << sizeof(a2) << " " << sizeof(a3) << endl;
   cout << (char*)(&a1 + 1) - (char*)&a1 << " ";
   cout << (char*)(&a2 + 1) - (char*)&a2 << " ";
   cout << (char*)(&a3 + 1) - (char*)&a3 << " ";
   cout << (char*)(&a + 1) - (char*)&a << endl;
   cout << (char*)(a1 + 1) - (char*)a1 << " ";
   cout << (char*)(a2 + 1) - (char*)a2 << " ";
   cout << (char*)(a3 + 1) - (char*)a3 << " ";
   cout << (char*)(a + 1) - (char*)a << endl;
   cout << (char*)(&a[0][0][0] + 1) - (char*)&a[0][0][0] << " ";
   cout << (char*)(&a[0][0] + 1) - (char*)&a[0][0] << " ";
   cout << (char*)(&a[0] + 1) - (char*)&a[0] << " ";
   cout << (char*)(&a + 1) - (char*)&a << endl;
   cout << (a[0][0][0] + 1) - a[0][0][0] << " ";
   cout << (char*)(a[0][0] + 1) - (char*)a[0][0] << " ";
   cout << (char*)(a[0] + 1) - (char*)a[0] << " ";
   cout << (char*)(a + 1) - (char*)a;
}
Copy after login

To solve this problem, we can follow some important points:

  • Integer size is 4 bytes (32 bits), pointer The size is 8 bytes. If we add 1 to the pointer, it will point to the next immediate type.

  • The type of &a1 is int **, &a2 is int ***, and the type of &a3 is int ****. Here are all pointers. If we add 1, we will add 8 bytes.

  • a [0] [0] [0] is an integer, &a [0] [0] [0] is int *, a [0] [0] is int * , the type of &a[0][0] is int(*)[6], and so on. So the type of &a is int(*)[4][5][6].

Output

480 8 8 8
8 8 8 480
4 8 8 120
4 24 120 480
1 4 24 120
Copy after login

The above is the detailed content of A C/C++ pointer puzzle?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template