繁体   English   中英

C Struct与指向数组的指针

[英]C Struct with pointer to array

我有以下代码,我有点困惑为什么我得到一个分段错误。

typedef struct {
  int tag;
  int valid;
} Row;

typedef struct {
  int index;
  int num_rows;
  Row **rows;
} Set;

/* STRUCT CONSTRUCTORS */

// Returns a pointer to a new Sow.
// all fields of this row are NULL
Row* new_row() {
  Row* r = malloc(sizeof(Row));
  return r;
}

// Returns a pointer to a new Set.
// the set's index is the given index, and it has an array of
// rows of the given length.
Set* new_set( int index, int num_rows, int block_size ) {
  Set* s = malloc(sizeof(Set));
  s->index = index;
  s->num_rows = num_rows;

  Row* rows[num_rows];
  for (int i = 0; i < num_rows; i++) {
    Row* row_p = new_row();
    rows[i] = row_p;
  }
  s->rows = rows;

  return s;
}

/* PRINTING */

void print_row( Row* row ) {
  printf("<<T: %d, V: %d>>", row->tag, row->valid);
}

void print_set( Set* set ) {
  printf("[ INDEX %d :", set->index);


  for (int i = 0; i < set->num_rows; i++) {
    Row* row_p = set->rows[i];
    print_row(row_p);
  }

  printf(" ]\n");
}


int main(int argc, char const *argv[]) {

  Set* s = new_set(1, 4, 8);
  print_set(s);


  return 0;

}

基本上, Set有一个指向Row数组的指针。 我想Row* row_p = set->rows[i]; 从集合中获取行是正确的方法,但我必须遗漏一些东西。

您正在分配Row*的本地数组

  Row* rows[num_rows];
  for (int i = 0; i < num_rows; i++) {
    Row* row_p = new_row();
    rows[i] = row_p;
  }
  s->rows = rows;

并让Setrows指针指向该指针。 函数返回后,本地数组不再存在,因此s->rows就是一个悬空指针。 返回函数后仍然有效的内存必须使用malloc (或其中一个表兄弟)进行分配。

s->rows在函数new_set()分配了局部变量rows的地址,这意味着当new_set()返回时, s->rows是一个悬空指针 动态分配Row*数组以纠正:

s->rows = malloc(num_rows * sizeof(Row*));
if (s->rows)
{
    /* for loop as is. */
}

请记住, s->rows及其元素必须是free() d。

暂无
暂无

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

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