多维字符数组 - 如何用随机字符填充它?
所以我尝试创建一个像这样的生成器:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
char* data;
void genRandomFilledChar(char *s, int i, int j, int k) {
const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int q = 0; q < i; ++q) {
for (int w = 0; w < j; ++w) {
for (int e = 0; e < k; ++e) {
s[e] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
} }}
int main()
{
data = new char[10000][10000][10000];
genRandomFilledChar(data, 10000, 10000, 10000);
cin.get();
return 0;
}
但它无法编译。我做错了什么?
So I have tried to create a generator like:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
char* data;
void genRandomFilledChar(char *s, int i, int j, int k) {
const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int q = 0; q < i; ++q) {
for (int w = 0; w < j; ++w) {
for (int e = 0; e < k; ++e) {
s[e] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
} }}
int main()
{
data = new char[10000][10000][10000];
genRandomFilledChar(data, 10000, 10000, 10000);
cin.get();
return 0;
}
But it fails to compile. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C多维数组只是一种自动计算索引的方法。
为什么不声明 char data[i*j*k] (或使用 new 从堆中获取)然后将其填充为单维?您稍后可以将 [][][] 索引与数据一起使用。
C multidimensional arrays are just a way to calculate index automatically.
Why not declare char data[i*j*k] (or get from heap with new) and then fill it as if it is single dimension? You can later use [][][] indexes with data.
您不能像这样分配新数组。您应该声明适当大小的一维数组或创建指向数组的指针数组。
或者
genRandomFilledChar
也有错误。每次仅使用随机值填充前 10000 个字符。还有,最后一个。对于
rand()
,您需要使用srand
初始化随机生成器。You can't allocate new array like you do. You should declare one dimensional array of proper size or create array of pointers to pointer to array.
or
Also you have error in
genRandomFilledChar
. You fill only first 10000 chars with random values every time.And, the last. For
rand()
you need to initialize random generator withsrand
.都错了。首先,三维字符数组是
char***
。接下来,您需要分 3 步初始化该内存。Are wrong. First, a three dimensional array of chars is
char***
. Next, you need to initialize that memory in 3 steps.应该是
因为它是一个3维数组
should be
because it is a 3 dimensional array
因为
new char[10000][10000][10000]
的类型为char (*)[10000][10000]
,而不是char*
,数据
的类型。我想你想要的是Because
new char[10000][10000][10000]
has the typechar (*)[10000][10000]
, notchar*
, the type ofdata
. And I think what you want is