Я новичок в C ++, у меня большой опыт работы с Objective-C.
Я пытаюсь получить массив c-строк (то есть char **
) в качестве переменной экземпляра в моем классе, который выделяется и заполняется в моем конструкторе, а затем в другой функции-члене, которую я хочу распечатать вся "сетка".
Распределение работает, я заполняю свой массив строками (пока просто "aaaaaaa" и так далее). Проверяя в конце моего конструктора, я вижу, что каждая строка была успешно создана и заполнена, как и ожидалось.
Однако затем я вызываю свою функцию printGrid (), и затем все становится странным. Если у меня есть 25 строк для печати, скажем, первые 12 или около того будут печатать мусор, а остальные 13 распечатать как положено. Похоже, что я где-то попираю память и не знаю, где.
Мой код может выглядеть немного неопрятно, потому что я пробовал разные вещи, поэтому я постараюсь сделать его как можно более сплоченным.
main.cpp: где я вызываю функции
#include <iostream>
#include "Bitmap.h"
using namespace std;
int main (int argc, char * const argv[]) {
Bitmap bitmap(15, 25);
bitmap.printBitmap();
return 0;
}
Bitmap.h: заголовок для моего класса
class Bitmap {
private:
char **_bitmap;
void printLine(char const*lineString);
int _width;
int _height;
public:
Bitmap();
Bitmap(int width, int height);
void printBitmap();
};
Bitmap.cpp: где происходит действие
#include <iostream>
#include "Bitmap.h"
using namespace std;
Bitmap::Bitmap() {
// allocate space for the bitmap
int numRows = 20;
int numColumns = 30;
Bitmap(numRows, numColumns); // Can I even safely do this? I'm not using the default constructor in my main() but I'm still curious.
}
Bitmap::Bitmap(int width, int height) {
_width = width;
_height = height;
_bitmap = (char **)malloc(sizeof(char*) * height); // FIXED this line (used to be char, now it's char *).
for (int currentRow = 0; currentRow < height; currentRow++) {
_bitmap[currentRow] = (char *)malloc((sizeof(char) * width));
snprintf(_bitmap[currentRow], width, "%s", "1");
for (int currentColumn = 0; currentColumn < width; currentColumn++) {
_bitmap[currentRow] = strcat(_bitmap[currentRow], "a");
}
printf("currentRow %0d: %s\n",currentRow, _bitmap[currentRow]); // Each row prints out FINE here, as expected
}
}
void Bitmap::printBitmap() {
int numColumns =_width;
int numRows = _height;
if (NULL == _bitmap)
return;
// iterate over the bitmap, line by line and print it out
for (int currentRow = 0; currentRow < numRows; currentRow++) {
// If there are, say, 25 lines, the first 12 or so will be garbage, then the remaining will print as expected
printLine((char const *)_bitmap[currentRow]);
}
}
void Bitmap::printLine(char const*lineString) {
printf(":%s\n", lineString);
}
Это для школы, и проф не допускает векторы или строки C ++. В противном случае, да, я знаю, что я должен использовать их. Спасибо за все предложения.