c++中字符串使用sizeof()为什么始终输出的是32字节

为什么在c++中定义字符串变量, 使用sizeof()不管是初始化还是没有初始化输出字节数都是占32字节 ?

#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

int main(void) {
	string test1;
	string test2 = "Hellow World!";

	// sizeof(test1) -> 输出: 32
	cout << "test1 = " << sizeof(test1) << endl;

	 // sizeof(test2) -> 输出: 32
	cout << "test2 = " << sizeof(test2) << endl;

	system("pause");
	return 0;
}

输出结果

因为 string 变量, 是一种特殊的"对象", 在这个对象的内部, 保存了一个指针, 这个指针指向一块内存, 这个内存, 是用来存储对应的字符串; sizeof(string变量) 只是计算string 变量在内存中的空间大小, 也既是包含(指针 和 其它成员的内存空间大小); 并没有包含这个指针所指向的内存.

所以无论string 的字符串多长, 这个string 变量在内存中只占用32字节.

字符串长度可以使用 string变量.length() 或 string变量.size() 来计算

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Poco库将Base64字符串解码成字节数组可以分为以下几个步骤: 1. 引入Poco库头文件和命名空间: ```c++ #include "Poco/Base64Decoder.h" #include <iostream> using namespace Poco; using namespace std; ``` 2. 定义待解码的Base64字符串和解码后的字节数组: ```c++ string base64Str = "SGVsbG8gV29ybGQh"; vector<unsigned char> decodedBytes; ``` 3. 创建Base64解码器和输出流,并将解码后的字节输出到流: ```c++ Base64Decoder decoder; decoder.attach(new StringStream(base64Str)); char buffer[1024]; int bytesRead = decoder.read(buffer, sizeof(buffer)); while (bytesRead > 0) { for (int i = 0; i < bytesRead; i++) { decodedBytes.push_back(static_cast<unsigned char>(buffer[i])); } bytesRead = decoder.read(buffer, sizeof(buffer)); } ``` 4. 输出解码后的字节数组: ```c++ for (int i = 0; i < decodedBytes.size(); i++) { cout << static_cast<int>(decodedBytes[i]) << " "; } cout << endl; ``` 完整代码如下: ```c++ #include "Poco/Base64Decoder.h" #include <iostream> using namespace Poco; using namespace std; int main() { string base64Str = "SGVsbG8gV29ybGQh"; vector<unsigned char> decodedBytes; Base64Decoder decoder; decoder.attach(new StringStream(base64Str)); char buffer[1024]; int bytesRead = decoder.read(buffer, sizeof(buffer)); while (bytesRead > 0) { for (int i = 0; i < bytesRead; i++) { decodedBytes.push_back(static_cast<unsigned char>(buffer[i])); } bytesRead = decoder.read(buffer, sizeof(buffer)); } for (int i = 0; i < decodedBytes.size(); i++) { cout << static_cast<int>(decodedBytes[i]) << " "; } cout << endl; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值