C 结构操作需要一些解释
我有以下代码:C 结构操作需要一些解释,c,pointers,struct,C,Pointers,Struct,我有以下代码: //length, width, height typedef struct { float L, W, H; } TDim; //contains details for each geometrical form typedef struct { char *id; // each geometrical form has a unique id float volume; TDim *dim; } TForm; TForm* FormAlloc() { TForm *F
//length, width, height
typedef struct {
float L, W, H;
} TDim;
//contains details for each geometrical form
typedef struct {
char *id; // each geometrical form has a unique id
float volume;
TDim *dim;
} TForm;
TForm* FormAlloc()
{
TForm *F = (TForm*) malloc(MAX * sizeof(TForm));
F->id = (char*) malloc(MAX * sizeof(char));
F->dim = (TDim*) malloc(MAX * sizeof(TDim));
return F;
}
这是在更多结构中操作变量和指针的一个很好的练习
我想做的是,存储一些长方体的id(基本上是字母“F”,后跟1,2,3…),长度,宽度和高度,以计算其体积
我需要一些关于->
与
用法的解释 我知道
->
与地址和
与成员一起工作
在int main()
中,我有:
F[0].id = "F1"; //the first cuboid has the id "F1"
F[0].dim[0].L = 1; //the first cuboid has length = 11
//could have used F[0].dim->L = 1; as well?
F[0].dim[0].W = 2;
F[0].dim[0].H = 3;
F[1].id = "F2"; //the second cuboid has the id "F2"
F[1].dim[1].L = 4; //this is where it breaks down - SEG_FAULT (I've used gdb to catch it)
是什么导致该线路出现SEG_故障 在此函数中:
TForm* FormAlloc()
{
TForm *F = (TForm*) malloc(MAX * sizeof(TForm));
F->id = (char*) malloc(MAX * sizeof(char));
F->dim = (TDim*) malloc(MAX * sizeof(TDim));
return F;
}
您创建了TForm
的MAX
元素的动态数组,但随后仅为第一个元素的id
和dim
成员分配内存,因此在尝试将内存存储在第二个元素中时会出现segfault
您将需要以下内容:
TForm* FormAlloc(void)
{
TForm *F = malloc(MAX * sizeof(TForm));
if ( !F ) {
perror("couldn't allocate memory");
exit(EXIT_FAILURE);
}
for ( size_t i = 0; i < MAX; ++i ) {
if ( (F[i].id = malloc(MAX)) == NULL ) {
perror("couldn't allocate memory");
exit(EXIT_FAILURE);
}
if ( (F[i].dim = malloc(MAX * sizeof(TDim))) == NULL ) {
perror("couldn't allocate memory");
exit(EXIT_FAILURE);
}
}
return F;
}
t格式*格式(无效)
{
TForm*F=malloc(最大*sizeof(TForm));
如果(!F){
perror(“无法分配内存”);
退出(退出失败);
}
对于(尺寸i=0;i
最有可能的情况是,您不想在这三个方面都使用MAX
,也就是说,您需要与每个id
字符串中所需的TForm
元素数完全相同的可能性很低
其他更次要的观点:
malloc()
可以返回NULL
,您应该对此进行检查F[0].id=“F1”代码>应该是strcpy(F[0].id,“F1”)
或类似的,因为否则您将丢失对malloc()
ed的内存的引用malloc()
强制转换返回sizeof(char)
根据定义始终是1
,因此您可以省略它F[0].dim[0].L=1代码>vsF[0]。尺寸->L=1代码>
在这里,这两者是等价的。使用下标操作符dim[0]
会自动为您解除引用dim
,因此您可以使用
操作符获取元素(dim[n]
相当于C中的*(dim+n)
)。如果没有[0]
,dim
是一个直指针,因此您可以使用->
操作符。显然,当您想要访问数组中的其他元素时,第一种形式更方便。对于其他的,您必须替换F[0].dim[1].L=1代码>与(F[0].dim+1)->L=1
或类似,使用->
运算符,这是不必要的卷积。MAX定义为我要存储的最大长方体数。明白了,好先生!成功了!非常感谢。那么F[0].dim[0].L=1代码>vsF[0]。尺寸->L=1代码>?