sizeof操作得出奇怪结论
在学<<C++ Primer>>时,遇到一个sizeof的问题,希望高手能给我解答一下。
下面是程序:
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main()
{
int *pi = new int[12];
cout << "pi: " << sizeof(pi)
<<" *pi: " << sizeof(*pi)
<< endl;
string st1("foobar");
string st2("a mighty oak");
string *ps = &st1;
cout << "st1: " << sizeof(st1)
<<" st2: " << sizeof(st2)
<<" ps: " << sizeof(ps)
<<" *ps: "<<sizeof(*ps)
<< endl;
cout << "short: \t" << sizeof(short) << endl;
cout << "short*: \t" << sizeof(short*) << endl;
cout << "short&: \t" << sizeof(short&) << endl;
cout << "short[3]: \t" << sizeof(short[3]) << endl;
}
书上结果中有:
st1:12 st2:12 ps:4 *ps:12
为什么我用g++编译后得到的相应项的结果却是:
st1: 4 st2: 4 ps: 4 *ps: 4
难不成是作者搞错了,我想应该不太可能吧。还是不同的编译器会有不同的结论?
下面是程序:
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main()
{
int *pi = new int[12];
cout << "pi: " << sizeof(pi)
<<" *pi: " << sizeof(*pi)
<< endl;
string st1("foobar");
string st2("a mighty oak");
string *ps = &st1;
cout << "st1: " << sizeof(st1)
<<" st2: " << sizeof(st2)
<<" ps: " << sizeof(ps)
<<" *ps: "<<sizeof(*ps)
<< endl;
cout << "short: \t" << sizeof(short) << endl;
cout << "short*: \t" << sizeof(short*) << endl;
cout << "short&: \t" << sizeof(short&) << endl;
cout << "short[3]: \t" << sizeof(short[3]) << endl;
}
书上结果中有:
st1:12 st2:12 ps:4 *ps:12
为什么我用g++编译后得到的相应项的结果却是:
st1: 4 st2: 4 ps: 4 *ps: 4
难不成是作者搞错了,我想应该不太可能吧。还是不同的编译器会有不同的结论?
...全文
相关推荐
奇怪的C语言特性
6. sizeof 操作符sizeof 操作符可以用于获取变量或类型的大小。在C语言中,sizeof(x) 可以获取x的大小,x可以是一个表达式或者类型名。如果x是一个表达式,不会执行运算。
关于new和delete的详细用法
”这种奇怪的写法便是placement new了,它实现了在指定内存地址上用指定类型的构造函数来构造一个对象的功能。
C++隐式转换问题分析及解决办法
* 使用 sizeof 运算符来检查变量的类型和大小。* 避免使用隐式转换,尽量使用显式类型转换。
memset的初浅体会
因此,实际上 npBuffer 数组中的每个元素可能不是 1,而是某个奇怪的值。那么,为什么 memset 函数不能正确地将数组元素设为某个特定的值呢?
C语言基础之malloc和free函数详解
堆是操作系统中一个用于动态分配内存的区域,由一系列连续的内存单元组成。当程序调用malloc()时,系统会在堆中找到足够大的空闲内存块并分配给程序。


