简体   繁体   English

静态分配的指向静态分配结构的指针数组

[英]Statically allocated array of pointers to statically allocated structures

In this program, there are 100 different runs.在这个程序中,有 100 次不同的运行。 For each run, an array of pointers needs to be created.对于每次运行,都需要创建一个指针数组。 The amount of pointers in each array is determined by a defined constant called NUM_POINTERS.每个数组中的指针数量由一个名为 NUM_POINTERS 的已定义常量决定。 The weird part about this program is that the array must be statically allocated, as well as the data that the pointers are pointing to.这个程序的奇怪之处在于必须静态分配数组,以及指针指向的数据。

This is my code:这是我的代码:

for (int j = 0; j < 100; j++){
    SomeType *arr[NUM_POINTERS];

    for (int k = 0; k < NUM_POINTERS; k++){
      SomeType blah;
      blah.data = NULL;
      arr[k] = &blah;
    }

}

Now this code does not work at all.现在这段代码根本不起作用。 It does not create a new array for every run, and if arr[1] is changed, then every other array element gets changed as well.它不会为每次运行创建一个新数组,如果 arr[1] 更改,那么每个其他数组元素也会更改。

I know that the easy way to fix this would be to use malloc, however that would be considered dynamically allocating, not statically.我知道解决此问题的简单方法是使用 malloc,但是这将被视为动态分配,而不是静态分配。 Is there any way to make it work while still having everything statically allocated?有没有办法让它工作,同时仍然静态分配所有东西?

Declare an array of pointers and an array of structures.声明一个指针数组和一个结构数组。 Then assign the pointers from the addresses of the structure array elements.然后从结构数组元素的地址分配指针。

Sometype *arr[NUM_POINTERS];
Sometype arr2[NUM_POINTERS];

for (int i = 0; i < NUM_POINTERS; i++) {
    arr[i] = &arr2[i];
}

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

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