【发布时间】:2011-01-20 18:06:11
【问题描述】:
我是 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++ 向量或字符串。否则,是的,我知道我应该使用这些。谢谢大家的建议。
【问题讨论】:
-
只是出于好奇:如果您使用 C++ 编写此代码,为什么不使用可用的功能,例如新建/删除等?
-
.....这是c++?我可以看到你已经掌握了 c 风格的 c++ 和 c++ 的大杂烩——考虑投资一本好的 c++ 书! ;)
malloc在 C++ 领域是一个faux-pas,考虑使用std::vector -
@Sagekilla:这里不是
new/delete。std::vector<std::string>是 OP 真正应该在这里使用的。 -
...这里有个提示-
calloc()还将初始化分配给一个字符的块(内部循环中的每一件事都在做什么)-所以一行:_bitmap[currentRow] = (char *)calloc('a', (sizeof(char) * width));-注意:这不会是一个空终止的字符串,所以你仍然应该 NUL 正确地终止它...... -
@jbrennan:然后重新制作一个基本的
std::vector。
标签: c++ arrays memory-management cstring