Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;:若指针int的大小只有4,它如何容纳数组?_C++ - Fatal编程技术网

C++ C++;:若指针int的大小只有4,它如何容纳数组?

C++ C++;:若指针int的大小只有4,它如何容纳数组?,c++,C++,看看这个节目。ptr如何获取阵列中的所有内容?我有点困惑 #include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr = arr; // sizof(int) * (number of element in arr[]) is printed printf("Size of arr[] %d\n", sizeo

看看这个节目。ptr如何获取阵列中的所有内容?我有点困惑

  #include <stdio.h>
    int main()
    {
       int arr[] = {10, 20, 30, 40, 50, 60};
       int *ptr = arr;

       // sizof(int) * (number of element in arr[]) is printed
       printf("Size of arr[] %d\n", sizeof(arr));

       // sizeof a pointer is printed which is same for all type 
       // of pointers (char *, void *, etc)
       printf("Size of ptr %d", sizeof(ptr));
       return 0;

}
#包括
int main()
{
int arr[]={10,20,30,40,50,60};
int*ptr=arr;
//已打印sizof(int)*(arr[]中的元素数)
printf(“arr[]%d\n的大小”,sizeof(arr));
//打印指针的大小,所有类型的指针大小相同
//指针类型(char*、void*等)
printf(“ptr%d的尺寸”,尺寸(ptr));
返回0;
}
ptr
将“引用”数组的第一个元素


通过向基指针地址值“添加”来访问其他每个元素,元素的大小乘以索引。指针只是一个表示数组开头的内存地址的数字。它不包含关于数组本身的任何信息,因此它指向的数组的大小没有限制。

在本声明中

int *ptr = arr;
指针
ptr
由数组
arr
的第一个元素的地址初始化

类似于
*(ptr+i)
的编译器考虑这样的表达式,其中
ptr+i
产生指向数组
arr
的第i个元素的指针

这导致您甚至可以编写
i[ptr]
而不是
ptr[i]
,因为在这两个表达式中使用了相同的指针算法

举个例子

std::cout << 6["Hello CMan"] << std::endl;

std::coutptr的类型是
int*
,因此sizeof返回用于在内存中存储指针的字节数。它不返回数组的大小。

您可以在下面的链接中找到这个问题的答案(可能不止这个):

std::cout << &6["Hello CMan"] << std::endl;