首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

malloc 的迷惑

2013-10-27 
malloc 的疑惑malloc 的疑惑#define MINLEN 256struct Center{double valuestruct Center * next}//想

malloc 的疑惑
malloc 的疑惑

#define MINLEN 256
struct Center
{
double value;
struct Center * next;
};

//想要给分配的内存赋值。
Center *pVecCenter = (Center *)malloc(MINLEN * sizeof(Center) );
for (int i = 0; i <num; i++)
{
Center tmpCenter;
tmpCenter.value = (double) i;
tmpCenter.next = NULL;
*(pVecCenter + i).value = (double) i;
*(pVecCenter + i).next = NULL;
}


出现:
error C2228: “.value”的左边必须有类/结构/联合
1>          类型是“Center *”
1>          是否改用“->”?
error C2228: “.next”的左边必须有类/结构/联合
1>          类型是“Center *”
1>          是否改用“->”?



问题一:
改为:下面就好了,请问这是什么原因呢? 上面的报错说的是什么呢?
(pVecCenter + i)->value = (double) i;
(pVecCenter + i)->next = NULL;

问题2:
用 free(pVecCenter) 就能把分配的内存删掉了吗?free怎么会知道分配的内存空间有多少?难道说指针pVecCenter能够知道分配的内存空间的范围吗?
malloc 内存 c 指针
[解决办法]
引用:
Quote: 引用:

问题1 
tmpCenter.value = (double) i; 
(pVecCenter + i)->value = (double) i;
->是指针指向其成员的运算符
.是结构体的成员运算符


为什么不能用
*(pVecCenter + i).value = (double) i; 呢?

可以这么用吧 但是你要这么用吧
我没测试 我也很久没敲这样的代码了
. 和*的优先级是.大于* 且结和性不同
(*(pVecCenter + i)).value = (double) i;
[解决办法]
跟Associativity无关,是优先级的问题,.比*在这里的优先级高。

这样就可以:
(*(pVecCenter + i)).value = (double) i; 

更常见的是:

(pVecCenter + i))->value = (double) i; 

热点排行