如何初始化一个二维数组成员变量
想在一个类中
class A
{
public:
A( char** );
private:
char **str;
};
A a( "saf ", "SF " );
A b( "d ", "SFF ", "SDF " );
就是想如上所示,str的维数不固定,每维长度也不固定,所以我只能用指针写了
但编不过去,不知道有没有什么好方法解决
[解决办法]
这种情况建议楼主用vector <string> 。
如果只是接一堆字符串的话,我看不出非要用char**的理由。
#include <vector>
#include <string>
using namespace std;
[解决办法]
#include <cstdio>
class A
{
public:
A( char** s) : str(s) {}
void print();
private:
char **str;
};
void A::print()
{
for (int i = 0; str[i] != NULL; i++) {
printf( "%s\n ", str[i]);
}
}
char *a1[] = { "hello ", "world ", NULL };
char *b1[] = { "oh ", "my ", "God ", NULL };
int main()
{
A a(a1);
A b(b1);
a.print();
b.print();
return 0;
}
[解决办法]
维数不确定,
那么直接使用 2 级指针也不是办法。
可以使用 1级指针,
进行多维模拟,
因为 类似数组, 所谓的 维,只是逻辑概念,物理存储还是顺序的,也就是1维的,故可以使用1维指针模拟 ~~
[解决办法]
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include <conio.h>
class A
{
public:
A(unsigned int size,...);
void Output();
~A();
private:
char **str;
unsigned int size;
};
A::A(unsigned int size,...)
{
va_list vl;
this-> size = size;
assert(size> 0);
str = (char**)malloc(size*sizeof(char*));
assert(str!=NULL);
va_start(vl, size);
for(int j = 0;j <size;j++)
{
char *p = va_arg( vl, char*);
if((str[j] = strdup(p))==NULL)
{
//error
}
}
va_end(vl);
}
void A::Output()
{
puts( "============================================================ ");
for(int i = 0;i <size;i++)
{
printf( "%s\n ",str[i]);
}
puts( "============================================================ ");
}
A::~A()
{
for(int i = 0;i <size;i++)
{
free((void*)str[i]);
}
free(str);
}
int main(int argc,char *argv[])
{
A a(2, "saf ", "SF ");
a.Output();
A b(3, "d ", "SFF ", "SDF ");
b.Output();
getch();
}