0

我想在 C++ 中创建锯齿状字符二维数组。

int arrsize[3] = {10, 5, 2};
char** record;
record = (char**)malloc(3);
cout << endl << sizeof(record) << endl;
for (int i = 0; i < 3; i++) 
{
    record[i] = (char *)malloc(arrsize[i] * sizeof(char *));
    cout << endl << sizeof(record[i]) << endl;
}

我想设置record[0]名称(应该有 10 个字母)、record[1]标记(应该有 5 位标记)和record[3]ID(应该有 2 位数字)。我该如何实施?我直接将记录数组写入二进制文件。我不想使用structand class

4

4 回答 4

5

在 C++ 中它会是这样的:

std::vector<std::string> record;
于 2011-11-03T06:47:52.537 回答
2

Why would you not use a struct when it is the sensible solution to your problem?

struct record {
   char name[10];
   char mark[5];
   char id[2];
};

Then writing to a binary file becomes trivial:

record r = get_a_record();
write( fd, &r, sizeof r );

Notes:

  • You might want to allocate a bit of extra space for NUL terminators, but this depends on the format that you want to use in the file.

  • If you are writing to a binary file, why do you want to write mark and id as strings? Why not store an int (4 bytes, greater range of values) and a unsigned char (1 byte)

If you insist on not using a user defined type (really, you should), then you can just create a single block of memory and use pointer arithmetic, but beware that the binary generated by the compiler will be the same, the only difference is that your code will be less maintainable:

char record[ 10+5+2 ];
// copy name to record
// copy mark to record+10
// copy id to record+15
write( fd, record, sizeof record);
于 2011-11-03T08:48:04.310 回答
0

实际上“to malloc”的正确模式是:

T * p = (T *) malloc(count * sizeof(T));

whereT可以是任何类型,包括char *. 所以在这种情况下分配内存的正确代码是这样的:

int arrsize[3] = { 10, 5, 2 };
char** record;
record = (char**) malloc(3 * sizeof(char *));
cout << sizeof(record) << endl;
for (int i = 0; i < 3; ++i) {
    record[i] = (char *) malloc(arrsize[i] * sizeof(char));
}

我删除了 cout'ing sizeof(record[i]),因为它总是会产生(一个)指向 char 的指针的大小(在我的笔记本电脑上为 4)。sizeof 是在编译时播放的东西,并且不知道在执行时分配了多少指向的内存record[i](实际上是指针类型)。char *

于 2011-11-03T07:07:06.917 回答
0

malloc(3)分配 3 个字节。您的锯齿状数组将是一个包含指向字符数组的指针的数组。每个指针通常占用 4 个字节(在 32 位机器上),但更正确sizeof(char*)的是,因此您应该使用malloc(3 * sizeof(char*) ).

然后record[i] = (char*)malloc((arrsize[i]+1) * sizeof(char)),因为一个字符串是 a char*,一个字符是 a char,并且因为每个 C 风格的字符串通常都以一个'\0'字符结尾来表示它的长度。你可以没有它,但它会更难使用,例如:

strcpy(record[0], name);
sprintf(record[1], "%0.2f", mark);
sprintf(record[2], "%d", id);

填写你的记录,因为在最后sprintf放了一个\0。我假设mark是一个浮点数并且id是一个整数。

至于将所有这些写入文件,如果文件是二进制文件,为什么首先将所有内容都作为字符串放入?假设你这样做,你可以使用类似的东西:

ofstream f("myfile",ios_base::out|ios_base::binary);
for (int i=0; i<3; i++)
    f.write(record[i], arrsize[i]);
f.close();

话虽如此,我赞同安德斯的想法。如果您使用 STL 向量和字符串,您将不必处理丑陋的内存分配,并且您的代码也可能看起来更干净。

于 2011-11-03T07:08:19.607 回答