C ++数组大小不同的结果 [英] C++ array size different result
本文介绍了C ++数组大小不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
使用C编程语言的数组的大小?
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
string a[] = {"some", "text"};
void test(string a[])
{
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a;
}
int _tmain(int argc, _TCHAR* argv[])
{
test(a); //gives 0
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a; //gives 2
return 0;
}
正如您在评论中看到的,test(a)给出的是0而不是我期望的2.有人可以解释为什么以及如何纠正它吗?谢谢
as u can see in the comment test(a) gives 0 instead of 2 as i would expect. Could someone explain why and how could i correct it? thanks
推荐答案
将数组传递给函数时,它会衰减为指向数组第一个元素的指针,因此在您的 test(string a [])
函数
When you pass an array to a function, it decays to a pointer to the first element of the array and so within your test(string a[])
function
sizeof(a);
实际上返回的是指针的大小,而不是数组的大小.
actually returns the size of a pointer and not the size of your array.
这篇关于C ++数组大小不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文