繁体   English   中英

使用内存分配的结构指针

[英]struct pointer by using memory allocation

我陷入该代码中,如何为该结构分配内存

typedef struct {
  int a, b, c, d;
} FourInts;


void fillArray(int* array, int len) {
  printf("Filling an array at address %p with %d "
         "values\n", array, len);
  for (int i = 0; i < len; ++i) {
    array[i] = (i * 3) + 2;
    // assert() verifies that the given condition is true
    // and exits the program otherwise. This is just a
    // "sanity check" to make sure that the line of code
    // above is doing what we intend.
    assert(array[i] == ( (i * 3) + 2) );
  }
  printf("Done!\n");
}


/***********from here the problem *******/
struct FourInts *heap_struct_FourInts = (FourInts*) malloc(sizeof( FourInts) * 1);

  fillArray(heap_struct_FourInts->*a), 4);


  free(heap_struct_FourInts);

编译器给我那个错误

   arrays.c:222:43: warning: initialization from incompatible pointer type [enabled by default]
   struct FourInts *heap_struct_FourInts = (FourInts*) malloc(sizeof( FourInts) * 1);
                                           ^
arrays.c:224:33: error: dereferencing pointer to incomplete type
   fillArray(heap_struct_FourInts->a, 4);
                             ^

struct和malloc的代码中有什么错误?

要解决的第一个警告丢弃struct从可变类型,因为它不是一种struct ,而是一个typedef用于struct (因此,对于警告类型不匹配)。 对于错误,使用&heap_struct_FourInts->a传递结构中第一个int的地址。

但是,由于int在内存中不必是连续的,因此代码可能会调用未定义的行为。 例如,可以将编译器默认配置为填充8个字节的边界,在这种情况下,每个int之后将有4个未使用的字节(假设我们使用的平台具有4个字节int )。 阅读有关struct填充的更多信息。 这种特定的填充是非常不可能的情况,但是要记住这一点。

以下函数调用不正确:

fillArray(heap_struct_FourInts->*a), 4);

aint ,而不是一个指针int ,所以你不能取消对它的引用。 (即使它是一个指向int的指针,您的语法也不正确)。

另外,在您的结构中...

typedef struct {
    int a, b, c, d;
} FourInts;

...您不是在声明4个int的数组,而是四个独立的int 如果您希望a是长度为4的int数组,则需要这样声明:

typedef struct {
    int a[4], b, c, d;
} FourInts;

现在您可以像这样调用函数:

FourInts *heap_struct_FourInts = malloc(sizeof(*heap_struct_FourInts);
fillArray(heap_struct_FourInts->a), 4);

以下是等效的:

fillArray((*heap_struct_FourInts).a), 4);

暂无
暂无

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

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