简体   繁体   English

C / C ++中的指针可以编译,但是会出现段错误

[英]Pointers in C/C++ compiles but gives segfault error

Here's a code snipped that I have for a larger program 这是我为较大程序编写的代码片段

double *pos_x_h[224];
double *pos_y_h[224];
const double A = 1;         
const int N = 224;
double d_0;       
double alpha;     


void initialize(double nu, int rows = 16, int columns = 14) {  
    double d = 1 / double(columns);
    d_0 = d * (1 - pow(2.0, nu - 8));
    alpha = d - d_0;
    double dx = d;
    double dy = d * sqrt(3.0) / 2;

    for (int j = 0; j < rows; j++) {
        for (int i = 0; i < columns; i++) {
            int n = i + j * columns;
            *pos_x_h[n] = i * dx + (j % 2) * dx / 2.0;
            *pos_y_h[n] = j * dy;
        }
    }
}

int main(int argc, char *argv[]) {
    double nu=7.5;
    int rows=16;
    int columns=14;

    initialize(nu);

return 0;
}

The code compiles but it is gives a seg fault error. 代码可以编译,但是会给出段错误。 Can't see why that's the case. 无法理解为什么会这样。 Am I going over array_size? 我要检查array_size吗?

There doesn't seem to be any point in utilizing pos_x_h and pos_y_h as pointer arrays. 利用pos_x_hpos_y_h作为指针数组似乎没有任何意义。

Change this: 更改此:

double *pos_x_h[224];
double *pos_y_h[224];

To this: 对此:

double pos_x_h[224];
double pos_y_h[224];

And this: 和这个:

*pos_x_h[n] = i * dx + (j % 2) * dx / 2.0;
*pos_y_h[n] = j * dy;

To this: 对此:

pos_x_h[n] = i * dx + (j % 2) * dx / 2.0;
pos_y_h[n] = j * dy;

If you really insist on utilizing pointer arrays, then you can use this (in addition to the above): 如果您确实坚持使用指针数组,那么可以使用它(除了上面的方法):

double *pos_x_h_ptr[224];
double *pos_y_h_ptr[224];
for (int n=0; n<224; n++)
{
    pos_x_h_ptr[n] = pos_x_h+n;
    pos_y_h_ptr[n] = pos_y_h+n;
}
double *pos_x_h[224];
double *pos_y_h[224];

are arrays of pointers, but you use them wihtout allocating memory 是指针数组,但是在分配内存时使用它们

*pos_x_h[n] = i * dx + (j % 2) * dx / 2.0;
*pos_y_h[n] = j * dy;

probably something like that 大概是这样的

 pos_x_h[n] = malloc(sizeof(double));
 *pos_x_h[n] = i * dx + (j % 2) * dx / 2.0;
 pos_y_h[n] = malloc(sizeof(double));
 *pos_y_h[n] = j * dy;  

if you need to alocate memory outside the initialize function (why would you? it is init function) you can do it in main 如果您需要在初始化函数之外分配内存(为什么呢?它是init函数),则可以在main函数中进行

  int i = 0;
  for(;i< 224;++i)
  {
      pos_x_h[i] = malloc(sizeof(double));
      pos_y_h[i] = malloc(sizeof(double));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM