为什么通过转换动态分配结构不起作用?
Why Dynamic Allocation of a Struct by casting doesn't work?
我有以下结构:
typedef struct ${
char author[27];
char iso[2];
int nrVolumes;
TVolume* volume; //this is another struct
}TAuthor;
我需要一个函数来 return 指向 TAuthor 的指针。该函数将传递一个 int-nrVol-,它必须 return 一个指向 TAuthor 的指针,该指针具有 nrVolumes 字段 = nrVol。我已经完成了功能。
TAuthor* aloc1(int nrVol){
TAuthor* new = (TAuthor*)malloc(sizeof(TAuthor));
new->nrVolumes = nrVol;
return new;
}
这个按预期运行。
TAuthor* aloc2(int nrVol){
char* new = malloc(sizeof(TAuthor));
(TAuthor*)new->nrVolumes = nrVol;
return (TAuthor*)new;
}
编译时 "aloc2" 给我这个错误:
请求成员 'nrVolumes' 不是结构或联合
为什么我的转换不起作用?由于 "new" 只是一个字节数组,我想即使通过转换编译器也不知道哪个字节负责哪个字段,但我不确定这个
两个错误:
->
运算符的优先级高于强制转换运算符。
- 您不应从
char
数组转换为结构,因为这会引发严格的别名错误。 What is the strict aliasing rule?
直接用第一个版本就好了
您需要先将 new 类型转换为 TAuthor,然后将其指向其成员:
TAuthor* aloc2(int nrVol){
char* new = malloc(sizeof(TAuthor));
((TAuthor*)new)->nrVolumes = nrVol;
return (TAuthor*)new;
}
我有以下结构:
typedef struct ${
char author[27];
char iso[2];
int nrVolumes;
TVolume* volume; //this is another struct
}TAuthor;
我需要一个函数来 return 指向 TAuthor 的指针。该函数将传递一个 int-nrVol-,它必须 return 一个指向 TAuthor 的指针,该指针具有 nrVolumes 字段 = nrVol。我已经完成了功能。
TAuthor* aloc1(int nrVol){
TAuthor* new = (TAuthor*)malloc(sizeof(TAuthor));
new->nrVolumes = nrVol;
return new;
}
这个按预期运行。
TAuthor* aloc2(int nrVol){
char* new = malloc(sizeof(TAuthor));
(TAuthor*)new->nrVolumes = nrVol;
return (TAuthor*)new;
}
编译时 "aloc2" 给我这个错误: 请求成员 'nrVolumes' 不是结构或联合
为什么我的转换不起作用?由于 "new" 只是一个字节数组,我想即使通过转换编译器也不知道哪个字节负责哪个字段,但我不确定这个
两个错误:
->
运算符的优先级高于强制转换运算符。- 您不应从
char
数组转换为结构,因为这会引发严格的别名错误。 What is the strict aliasing rule?
直接用第一个版本就好了
您需要先将 new 类型转换为 TAuthor,然后将其指向其成员:
TAuthor* aloc2(int nrVol){
char* new = malloc(sizeof(TAuthor));
((TAuthor*)new)->nrVolumes = nrVol;
return (TAuthor*)new;
}