C 更改值而不是打印时出现分段错误
在下面的代码中,我初始化了另一个结构中的结构数组。初始化数组后,我可以在循环#1中毫无问题地打印所有值 但是,如果我尝试更改值,如在循环#2中,当尝试访问正好位于数组中间的元素时(即,当j==points/2,或在这种特殊情况下为50),我会遇到分段错误 为什么访问元素来打印它是有效的,但试图更改它会导致分割错误C 更改值而不是打印时出现分段错误,c,segmentation-fault,malloc,C,Segmentation Fault,Malloc,在下面的代码中,我初始化了另一个结构中的结构数组。初始化数组后,我可以在循环#1中毫无问题地打印所有值 但是,如果我尝试更改值,如在循环#2中,当尝试访问正好位于数组中间的元素时(即,当j==points/2,或在这种特殊情况下为50),我会遇到分段错误 为什么访问元素来打印它是有效的,但试图更改它会导致分割错误 #include <stdio.h> #include <stdlib.h> struct flux{ double *intense; double
#include <stdio.h>
#include <stdlib.h>
struct flux{
double *intense;
double *tau;
};
struct radius_struct{
int id;
struct flux *flux;
};
int main(int argc, const char * argv[]) {
int i,j, ichan, points,nchan;
points = 100;
nchan = 20;
struct radius_struct radius_struct;
radius_struct.id = 99;
radius_struct.flux = malloc(sizeof(double) * points);
for(i = 0; i < points; i++){
radius_struct.flux[i].intense= malloc(sizeof(double) * nchan);
radius_struct.flux[i].tau= malloc(sizeof(double) * nchan);
for(ichan=0;ichan<nchan;ichan++){
radius_struct.flux[i].intense[ichan] = ichan;
radius_struct.flux[i].tau[ichan] =ichan;
}
}
//Loop #1
for(j = 0; j < points; j++){
for(ichan=0; ichan<nchan; ichan++){
printf("%f %f\n", radius_struct.flux[j].intense[ichan], radius_struct.flux[j].tau[ichan]);
}
}
//Loop #2
for(j = 0; j < points; j++){
for(ichan=0; ichan<nchan; ichan++){
radius_struct.flux[j].intense[ichan] = 123.456;
radius_struct.flux[j].tau[ichan] = 123.456;
}
}
return 0;
}
#包括
#包括
结构通量{
双重*强烈;
双*头;
};
结构半径{
int-id;
结构通量*通量;
};
int main(int argc,const char*argv[]{
int i,j,ichan,points,nchan;
点数=100;
nchan=20;
结构半径\u结构半径\u结构;
半径_struct.id=99;
半径_struct.flux=malloc(sizeof(双)*点);
对于(i=0;i 对于(ichan=0;ichan,如注释中所指出的,radius_struct.flux为“struct flux”类型。
所以你所要做的就是更换
radius_struct.flux = malloc(sizeof(double) * points);
与
避免分配大小调整错误
分配到被引用对象的大小。更易于正确编码、查看和维护
// v------------v wrong size
// radius_struct.flux = malloc(sizeof(double) * points);
radius_struct.flux = malloc(sizeof *(radius_struct.flux) * points);
// ^--------------------------^ right size, even without looking up .flux type.
为什么在初始化过程中访问它们或在循环之前打印它们时它不会失败#2——
radius_struct.flux[i].sensitive
以及以下所有代码都是可疑的,并且会受到未定义行为的影响,因为之前的分配并不一定充分。有些东西可能有效,有些则可能无效。另请参阅
健壮的代码还将通过检查NULL
radius\u struct.flux=malloc(sizeof(double)*点);
?radius\u struct.flux=malloc(sizeof(double)*点)
:(sizeof(double)
是错误的,因为radius\u struct.flux
不是double
而是struct flux
。它应该是malloc(sizeof(*radius\u struct.flux)*点)
instead@Jabberwocky这解决了问题,非常感谢!为了更好地理解,既然分配不正确,为什么在初始化时访问它们或在循环#2之前打印它们时不会失败?@egarciab请务必阅读并理解第二条评论中的链接。egarciab,而不是询问“为什么在没有发布真实代码的情况下访问元素以打印它是有效的”,发布使用的代码比仅仅松散地引用它要好。在评论中还指出,应该避免使用malloc(sizeof(type))
,而使用malloc(sizeof*pointer)
。另外,解决OP的问题可能会很有趣:“为什么访问元素以打印它可以工作,但试图更改它会导致分段错误?”
// v------------v wrong size
// radius_struct.flux = malloc(sizeof(double) * points);
radius_struct.flux = malloc(sizeof *(radius_struct.flux) * points);
// ^--------------------------^ right size, even without looking up .flux type.