jbr*_*nan 1 c++ arrays memory-management cstring
我是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;
}
Run Code Online (Sandbox Code Playgroud)
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();
};
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
这是针对学校的,教授不允许使用C++向量或字符串.否则,是的我知道我应该使用那些.感谢所有的建议.
红色标志:
_bitmap = (char **)malloc(sizeof(char) * height);
Run Code Online (Sandbox Code Playgroud)
应该
_bitmap = (char **)malloc(sizeof(char*) * height);
Run Code Online (Sandbox Code Playgroud)
你想要一个指向a的指针char*,而不是指向a的指针char.
_bitmap = (char **)malloc(sizeof(char) * height);
Run Code Online (Sandbox Code Playgroud)
应该
_bitmap = (char **)malloc(sizeof(char*) * height);
Run Code Online (Sandbox Code Playgroud)
并且只有你编码C.
如果你绝对需要位图是连续的,那么更好的是使用new/delete
Vector< Vector < char > >
Run Code Online (Sandbox Code Playgroud)
如果你不这样做.
此外,strcat似乎是一个奇怪的选择,因为你还没有初始化内存.即不一定是0,所以字符串没有结束.这可能会导致你的记忆踩踏.尝试使用strcpy(如果你想要安全,请使用strncpy).