C++动态分配指针数组
发布日期:2022-03-03 10:44:06 浏览次数:9 分类:技术文章

本文共 1193 字,大约阅读时间需要 3 分钟。

#include "stdafx.h"#include 
#include
#include
using namespace std;int _tmain(int argc, _TCHAR* argv[]){ vector
ivec; ivec.push_back("Hello world"); ivec.push_back("Hello everybody!"); ivec.push_back("Hello my family!"); vector
::size_type size = ivec.size(); vector
::iterator itr = ivec.begin(); vector
::iterator end = ivec.end(); vector
::size_type vSize = ivec.size(); // vector的大小 char **chars = new char*[vSize]; // 动态分配字符指针数组 // 赋值操作左边有两个星号可理解为chars本身的元素是一个char*型, // new操作符又返回了一个指针指向字符数组,所以是char **chars // 注意赋值的右侧不能是new (char*)[vSize],没有在new后面加()的语法。 int i = 0; while (itr != end) { string str = *itr; // 从vector中得到下一个string const char* strContent = str.c_str(); // 将string转换为c风格字符串 size_t strLength = strlen(strContent); // 求字符串长度,不包含null字符 char *strArray = new char[strLength + 1]; // 为当前字符串动态分配一个数组 chars[i] = strArray; // 记录这个字符数组的首地址 // chars[i]相当与*(chars + i) for (int k = 0; k != strLength + 1; k++) { // 将字符串的内容拷贝到新的数组中 strArray[k] = strContent[k]; } ++itr; ++i; } for (int j = 0; j != 3; j++) { // 显示各字符串 cout << chars[j] << endl; delete[] chars[j]; // 释放字符数组 } delete[] chars; // 释放字符指针数组 return 0;}

转载地址:https://blog.csdn.net/yangjie6898862/article/details/51861840 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:信道特征(码元、比特、波特率等概念)
下一篇:平衡二叉树的简单建立--示例

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月17日 07时21分45秒