C数组在被函数修改后被破坏

时间:2017-01-23 13:42:44

标签: c arrays

我正在尝试编写一个C程序,它将所有通过特定条件的结构收集到一个数组中。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Book {
  char title[20];
  unsigned int published;
  char authors[50];
  unsigned int pages;
};

unsigned int get_books_from(unsigned int year, int length, struct Book data[], struct Book results[]);

int main(int argc, char* argv[]) {
  struct Book data[5];

  // Init book pool inside data

  struct Book books[0];
  unsigned int books_count = get_books_from(1973, 5, data, books);

  return 0;
}

unsigned int get_books_from(unsigned int year, int length, struct Book data[], struct Book results[]) {
  results = (struct Book*) malloc(sizeof(struct Book));
  unsigned int results_count = 0;

  int i;
  for (i = 0; i < length; i++) {
    if (data[i].published == year) {
      *(results + results_count) = data[i];

      results = (struct Book*) realloc(results, (++results_count + 1) * sizeof(struct Book));
    }
  }

  return results_count;
}

逻辑似乎工作正常,但是当试图访问books函数(称为get_books_from)之外的results数组内容时,所有数据都会被破坏。一些原始数据仍在那里但不在正确的位置,看起来好像数据已经移位。我查看了指向booksresults的指针,看起来这些变量在函数完成后并没有指向内存中的相同位置。可能是什么问题?

2 个答案:

答案 0 :(得分:5)

您的get_books_from在此处更改了results的值:

  results = (struct Book*) realloc(results, (++results_count + 1) * sizeof(struct Book));

但它无法让调用者获得results的新值。

更糟糕的是,您使用get_books_from拨打data,该main已在realloc的堆叠中分配。你不能realloc它。正如malloc的文档所述,您尝试重新分配的指针必须在之前调用callocreallocstruct Book data[5];时返回。幸运的是,你忽略了那个价值。但这使得main中的from enum import IntEnum class IndexGeneric(IntEnum): """ This enum holds the index value of genric object entrys """ DeviceType = 0x1000 ErrorRegister = 0x1001 Idx = IndexGeneric 难以理解。为什么要在堆栈上分配空间?

答案 1 :(得分:0)

除了另一个答案:

你可能想要这样的东西(未经测试,非错误检查代码,声明和为了简洁而省略#includes):

unsigned int get_books_from(unsigned int year, int length, struct Book data[], struct Book **results);

int main(int argc, char* argv[]) {
  struct Book data[5];

  // Init book pool inside data

  struct Book *books;
  unsigned int books_count = get_books_from(1973, 5, data, &books);

  return 0;
}

unsigned int get_books_from(unsigned int year, int length, struct Book data[], struct Book **results) {
  *results = (struct Book*) malloc(sizeof(struct Book));
  unsigned int results_count = 0;

  int i;
  for (i = 0; i < length; i++) {
    if (data[i].published == year) {
      *(*results + results_count) = data[i];

      *results = (struct Book*) realloc(*results, (++results_count + 1) * sizeof(struct Book));
    }
  }

  return results_count;
}
相关问题