我分配了一个结构体数组。在循环中,指向单独结构的指针然后检查是否需要更多结构。如果是这样,则使用realloc来增加结构数。但是,由于重新分配可能使用不同的内存块,因此必须将指向最后填充结构的旧指针更新到内存中的新位置。跟踪指针最后指向哪个数组的最佳方法是什么?下面的代码不起作用,它用realloc()暂停:无效的旧大小。为了清楚起见,我在分配后省去了对NULL的检查。

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

#define N 2
struct s
{
  int a;
};
struct s **p;

int main()
{
    struct s *q;
    int n = N;
    int i, j, m;

    p = malloc(n * sizeof(struct s *));
    for (i = 0 ; i < n ; i++)
        p[i] = malloc(sizeof(struct s));
    q = p[0];
    for (i = 0 ; i < 100 ; i++)
    {
        if ((m = q - p[0] + 1) > n)
        {
            printf("realloc at n %d\n", n);
            n *= 2;
            p = realloc(p, n * sizeof(struct s *));
            for (j = 0 ; j < n ; j++)
                p[j] = realloc(p[j], sizeof(struct s));
            q = p[m - 1];
        }
        q->a = i;
        q++;
    }
}

最佳答案

您分配了一个指针数组。使用标准C函数realloc时,它将旧数组中已经存在的值复制到新数组中。无需分配数组元素所指向的新对象。

该程序可以如下所示

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

#define N 2

struct s
{
    int a;
};

int main( void )
{
    struct s **p;
    int n = N;
    int i, j;

    p = malloc( n * sizeof( struct s* ) );

    for ( i = 0; i < n; i++ ) p[i] = malloc( sizeof( struct s ) );

    for ( i = 0; i < 100; i++ )
    {
        if ( i == n )
        {
            struct s **tmp = realloc( p, N * n * sizeof( struct s * ) );

            if ( !tmp ) break;

            p = tmp;
            n = N * n;

            for ( j = i; j < n; j++ ) p[j] = malloc( sizeof( struct s ) );
        }

        p[i]->a = i;
    }

    for ( i = 0; i < ( n < 100 ? n : 100 ); i++ )
    {
        printf( "%2d ", p[i]->a );
        if ( ( i + 1 ) % 10 == 0 ) printf( "\n" );
    }

    for ( i = 0; i < n; i++ ) free( p[i] );
    free( p );
}


它的输出是

 0  1  2  3  4  5  6  7  8  9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

关于c - 在重新分配的n个结构数组中跟踪结构i的指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35392505/

10-14 15:18
查看更多