#include <iostream>
using namespace std;
struct mumble //把单一元素的数组放在一个struct的尾端,即可实现拥有可变大小的数组
{
/*stuff*/
char pc[1];
}test2;
/*
struct mumble *p;
p = (struct mumble *)malloc(sizeof(char)*n);
则此时p->pc[]就是拥有n个元素的数组,结构mumble里面的成员pc指向该数组,即结构mumble可以拥有可变大小的数组
*/
int main()
{
char test1[2]={'1','2'};
test2.pc[0]='3';
char p[14] = {'4','5','6' };
memcpy(test1,p,3);
memcpy(&(test2.pc[0]),p,3);
cout<<"test1: "<<endl;
for(int i=0; i<3; i++)
{
cout<<test1[i]<<" ";
}
cout<<endl;
cout<<"test2:"<<endl;
for(int i=0; i<3; i++)
{
cout<<test2.pc[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
/*
运行结果如下
test1:
5 6 6
test2:
4 5 6
*/
//也就是说用数组的话,超界拷贝时会有错误,而用这个结构却不错
#include <iostream>
using namespace std;
struct mumble
{
char pc[1];
};
int main()
{
char *pstr = "hello world";
cout << sizeof(struct mumble) << endl; //输出1
struct mumble *pmumb1 = ( struct mumble* )malloc( sizeof( struct mumble ) + strlen(pstr)
+ 1 );
strcpy( &pmumb1->pc[0], pstr ); // pmumb1->pc[0]为pmumb1指向的内存空间中的第一个字节
cout << pmumb1->pc << endl; //会输出hello world
system("pause");
return 0;
}
struct mumble
{
/*stuff*/
char pc[1];
};
如果改成
struct mumble
{
/*stuff*/
char *pc;
};
两者一样吗?看不出来?:(没区别,但是如果改成
struct mumble
{
int i;
/*stuff*/
char pc[1];
};
和
struct mumble
{
int i;
/*stuff*/
char *pc;
};
就有区别了:前者的pc数组和变量i在内存里是相连的!而后者不是!
如果你:
struct mumble
{
int i;
/*stuff*/
char pc[1];
};
mumble *p=malloc(sizeof(int)+sizeof(char)*100);
则相当于
struct mumble
{
int i;
/*stuff*/
char pc[100];
};
而后者无论如何难以产生这个效果!比如在读写结构化文件的时候,这个技巧就非常有用。
注:《深入探索C++对象模型》P19-P20