高手指教malloc用法,分配二维结构体指针。

高手指教malloc用法,分配二维结构体指针。

相关代码如下:

struct s_Dip_Azimuth{

float fLine;

float fCmp;

float fTime;

float fDipX;

float fDipY;

float fAzimuth;

};

/*类型定义*/

typedef struct s_Dip_Azimuth sDA;
sDA **WhDataBuf1;

/*初始化*/
(49)*WhDataBuf1 = (sDA *)malloc(2300 * sizeof(sDA));
(50)WhDataBuf1 = (sDA *)malloc(1000 * sizeof(sDA));

程序编译时显示如下信息(VC++ 6.0环境下):
***.c(50) : warning C4047: '=' : 'struct s_Dip_Azimuth ** ' differs in levels of indirection from 'struct s_Dip_Azimuth *'
***.c(49) : warning C4700: local variable 'WhDataBuf1' used without having been initialized

请教高手,这个结构体指针应该如何初始化,并且最后如何释放内存(free函数)。
都不正确!
正确初始化方式是这样的:
WhDataBuf1 = (sDA **)malloc(2300 * sizeof(sDA));
for(i=0; i<2300; ++i) WhDataBuf1[i] = (sDA *)malloc(1000 * sizeof(sDA));

二维指针指针应该用for循环初始化。结束用for循环逐个释放。

假设定义sDA **p,准备初始化到p[12][12],则
1、初始化:
p = (sDA **)malloc(12* sizeof(sDA*));
for(int i=0;i<12;i++)
p[i] = (sDA*)malloc(sizeof(sDA));

2、释放:
for(int i=0;i<12;i++)free(p[i]);
free(p);

函数名: malloc
功 能: 内存分配函数
用 法: void *malloc(unsigned size);
程序例:

#include
#include
#include
#include

int main(void)
{
char *str;

/* allocate memory for string */
/* This will generate an error when compiling */
/* with C++, use the new operator instead. */
if ((str = malloc(10)) == NULL)
{
printf("Not enough memory to allocate buffer\n");
exit(1); /* terminate program if out of memory */
}

/* copy "Hello" into string */
strcpy(str, "Hello");

/* display string */
printf("String is %s\n", str);

/* free memory */
free(str);

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-03-31
*WhDataBuf1 = (sDA *)malloc(2300 * sizeof(sDA));
for(int i=0; i<2300; ++i) WhDataBuf1[i] = (sDA *)malloc(1000 * sizeof(sDA));
相似回答