C ++动态分配的静态尺寸数组的数组 [英] C++ dynamically allocated array of statically dimensioned arrays

查看:124
本文介绍了C ++动态分配的静态尺寸数组的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个结构,该结构包含可变数量的'char [2]',即2个字符的静态数组.

I need to create a structure that holds a variable number of 'char[2]'s, i.e. static arrays of 2 chars.

我的问题是,如何为x个char [2]分配内存.

My question is, how do I allocate memory for x number of char[2].

我尝试了此操作(假设定义了int x):

I tried this (assuming int x is defined):

char** m = NULL;
m = new char[x][2];
...
delete [] m;

(无效)

我意识到我可以使用std :: vector< char [2]>作为容器,但是我很好奇如何使用原始指针.

I realise I could use std::vector<char[2]> as a container, but I'm curious as to how it would be done with raw pointers.

我是C ++的新手,正努力学习.

I am very new to C++ and trying to learn.

推荐答案

在您的代码中,"m"的类型与您的新"调用不匹配.您想要的是:

In your code, the type of 'm' doesn't match your 'new' call. What you want is:

char (*m)[2] = NULL;
m = new char[x][2];
...
delete [] m;

m是指向2个字符的数组的指针,您调用new获得2个字符的x数组的数组,并将m指向第一个.

m is a pointer to arrays of 2 chars, and you call new to get an array of x arrays of 2 chars and point m at the first one.

这篇关于C ++动态分配的静态尺寸数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆