如何在c++中引用动态分配的字符数组
How to reference a dynamically allocated character array in c++
我需要了解如何在c++中操作动态分配的字符数组中不同索引位置的数据。我在发出嘎嘎声。我关心的变量是"items"
以下是Quack的类定义:
class Quack
{
public:
static const char YOUR_NAME[]; // used for printing out programmer's name
static const bool PREMIUM_VERSION; // used to designate Regular vs. Premium
Quack(int capacity, int growBy = 0);
// capacity: # of slots in array
// growBy: # of slots to add to array when it grows, 0 means "don't grow"
~Quack(void);
bool pushFront(const char ch); // push an item onto the front
bool pushBack(const char ch); // push an item onto the back
bool popFront(char& ch); // pop an item off the front
bool popBack(char& ch); // pop an item off the back
void rotate(int r); // "rotate" the stored items (see note below)
void reverse(void); // reverse the order of the stored items
int itemCount(void); // return the current number of stored items
void printArray(std::ostream& out) // print contents of array
{
unsigned int ch;
out << "[ ";
for (int i = 0; i < capacity; i++) {
ch = static_cast<unsigned char>(items[i]); // avoid sign extension
if (ch == '-') // print in hex, because using '-' for 0xCD
goto printHex;
else if (ch >= '!' && ch <= '}') // ASCII text character
out << static_cast<char>(ch) << ' ';
else if (ch == 0xCD) // print 0xCD as '-'
out << "- ";
else // print everything else as hex
goto printHex;
continue;
printHex:
out << std::setw(2) << std::setfill('0') << std::hex << ch << ' ';
}
out << ']' << std::endl;
}
private:
char *items;
int nItems;
int capacity;
int growBy;
int *front;
int *back;
public:
friend std::ostream& operator<<(std::ostream& out, Quack *q);
};
现在,这里是Quack构造函数:
Quack::Quack(int capacity, int growBy) :
capacity(capacity),
growBy(growBy),
nItems(0),
items(new char[capacity]),
front(NULL),
back(NULL)
{
}
我知道Quack的每个实例都有一个char变量"items",它是一个指向新字符数组的指针。我不明白的是如何引用数组中的项。例如,如果我想引用新字符数组的索引位置0,我说的是items(0)还是items[0],或者它是完全不同的东西?
感谢
items
是一个char数组,Quack
的每个实例都有自己的变量items
。访问动态分配的数组和静态分配的数组是相同的。它们被分配在连续的内存位置。
char arr[24]; // Allocate 24 bytes in contiguous memory locations in stack
char* arr = new char[24]; //Allocate 24 bytes in contiguous memory locations
// in heap
您可以通过以下任何方式访问变量:
1. Quack q;
cout << q.items << endl; //Print the char array
cout << q.items[1] << endl; // Print the second index position of items
2. Quack* qptr = new Quack();
cout << q->items << endl; //Print the char array
cout << q->items[1] << endl; // Print the second index position of items
相关文章:
- 使用动态分配将 char* 复制到另一个字符**
- 动态分配字符数组的内存
- C++具有动态分配的字符数组的结构
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 如何为结构字段动态分配字符空间
- 类的动态分配字符数组中的 WTF 行为
- 尝试创建指向动态分配的字符数组的指针
- 取消分配动态分配的字符数组的析构函数
- 如何在C++中动态分配全局字符数组中的类实例?
- 传递动态分配的 2D 字符数组会导致分段错误
- 从常量字符数组初始化为动态分配的常量字符数组
- 使用Strcpy_s复制动态分配的字符数组
- 将字符指针传递到函数中并动态分配内存
- 在类中动态分配C++字符数组
- C++ 从文本文件读取字符到动态分配的数组
- 如何在c++中引用动态分配的字符数组
- 动态分配缓冲区(字符字符串)大小 =i;使用马洛克
- 将动态分配的2d字符数组传递给函数
- 使用字符串或字符动态分配(数组)
- 动态分配内存给一个字符指针