我只是在乱搞并学习向量和结构,并且在某一点上,我尝试以字节为单位输出向量的大小.这是代码:
#include <iostream>
#include <vector>
struct Foo{
std::vector<int> a;
};
int main()
{
using std::cout; using std::endl;
Foo* f1 = new Foo;
f1->a.push_back(5);
cout << sizeof(f1->a) << endl;
cout << sizeof(f1->a[0]) << endl;
delete[] f1;
}
Run Code Online (Sandbox Code Playgroud)
输出是24和4.
显然第二行打印4,因为那是int的大小.但为什么另一个值24呢?向量是否占用24个字节的内存?谢谢!
有谁知道如何获得变量的内存大小(int,string,[]struct等),并打印出来?可能吗?
var i int = 1
//I want to get something like this:
fmt.Println("Size of i is: %?", i)
//Also, it would be nice if I could store the value into a string
Run Code Online (Sandbox Code Playgroud) 我遇到了一个问题,我需要找到数组的大小来确定数组的长度。我的理解是一个字符是 1 个字节,一个字符串是 2 个字节('\0'字符的额外字节)。
但是,我发现字符串数组的单个元素是 24 个字节。
我输出了一个字符串、字符和整数变量的大小来验证我的理解。我对 int、char 和 string 数组的单个元素做了同样的处理。
#include <iostream>
using namespace std;
int main()
{
string strArr[1] = {" "};
cout
<< sizeof " " << endl
<< sizeof strArr[0] << endl
<< sizeof strArr << endl << endl;
char charArr[1] = {'a'};
cout
<< sizeof 'a' << endl
<< sizeof charArr[0] << endl
<< sizeof charArr << endl << endl;
int intArr[1] = {1};
cout
<< sizeof 1 << endl
<< …Run Code Online (Sandbox Code Playgroud) 我的代码如下。当我检查值的地址时,它存储为280 288 290 298. 为什么要以这种模式存储?
package main
import "fmt"
func main() {
const a = 1111111111111111111
test := [7]int{a, 1, 33333,4,6,7,7}
fmt.Println(&test[0])
fmt.Println(&test[1])
fmt.Println(&test[2])
fmt.Println(&test[3])
fmt.Println(&test[4])
fmt.Println(&test[5])
fmt.Println(&test[6])
}
Run Code Online (Sandbox Code Playgroud)
输出 :
0xc00000e280
0xc00000e288
0xc00000e290
0xc00000e298
0xc00000e2a0
0xc00000e2a8
0xc00000e2b0
Run Code Online (Sandbox Code Playgroud)