在使用C中的数组中确定C
方法不正确的方法
list.size():
This method cannot be used because it is not a member function of the int array type.
- Determining the Size CorrectlyThe correct approach to determine the size of an array from a pointer is to pass the size as an additional argument.
- int最大(int *列表,int dist_index)
{
// ...
} 要使用此函数,将数组及其大小作为参数传递: = {1,2,2,2,3,4,5};
int size = sizeof(array) / sizeof(int); //计算阵列大小
int max =最大(数组,size);
c从c继承array/pointer等价,从而允许数组在传递到函数时腐烂到指针。此行为意味着指针包含没有大小的信息。
内存布局
理解数组的内存布局至关重要。声明数组时,将分配连续内存以存储其元素。指向第一个元素的指针意味着数组的开头,但没有带有有关其大小的信息。
从C中的指针中准确确定数组的大小,必须将大小作为附加参数传递到处理数组的功能的附加参数。此方法可确保该函数可以访问所需的信息。