stack — Как ссылаться на динамически размещенный массив символов в переполнении стека

Мне нужно понять, как манипулировать данными в различных позициях индекса в динамически размещенном символьном массиве в c ++. Я делаю кря (очередь / стек). Меня интересует переменная «items».

Вот определение класса для Кряка:

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], или это что-то совершенно другое?

Спасибо

0

Решение

Как вы правильно поняли, items является массивом символов и каждый экземпляр 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
0

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector