现在的位置: 首页 > 综合 > 正文

指向结构体的指针和指向结构体指针的指针

2019年08月08日 ⁄ 综合 ⁄ 共 784字 ⁄ 字号 评论关闭

刚才用结构体的指针,操作内存出错了,记录一下。

 

 

struct T *ptr;是指向一个结构体的指针,也可以当做一个结构体数组来用。 可以把结构体当做 int 来看,int* 类型即可以指向一个整数,

也可以指向数组。


struct T ** ptr, 说白了 就是一个结构体指针的数组,数组内都是指针,还要分配内存。

 

 

/*

struct T

{

int   num;

// char* name;

char name[10];

}*ptr;

 

 

void main( void )

{

 

int i;

 

ptr = (struct T* )malloc( 10 * sizeof( struct T)  );

 

for ( i=0; i<10 ; i++)

{

// ptr[i]->name = (char*) malloc( 10);

// if ( ptr[i]->name == NULL)

// {

// cout<<"malloc error"<<endl;

// }

strcpy( ptr[i].name,"test");

ptr[i].num = i ;

}

 

for( i = 0 ;i <10 ;i++ )

{

cout<<ptr[i].name<<"/t"<<ptr[i].num<<endl;

}

 

}

 

*/

 

struct T

{

char*   name;

int    num;

 

}**ptr;

 

 

void main( void )

{

int i = 0;

ptr=(struct T **)malloc(10*sizeof(struct T*));

for (  ;i <10; i++)

{

ptr[i] = (struct T* )malloc( 10* sizeof( struct T));

ptr[i]->name = (char*) malloc(10);

strcpy(ptr[i]->name,"test");

ptr[i]->num = i;

}

for ( i = 0 ; i < 10; i++)

{

cout<<ptr[i]->name<<"/t"<< ptr[i]->num<<endl;

}

 

}

抱歉!评论已关闭.