简体   繁体   中英

2D array of structs in heap memory C

I keep getting a segfault when I try to initialize a 2D array of structs in dynamic memory. I know a 1D array of structs is technically a pointer to a pointer, I figured a 2D array of structs also functioned that way, but it seems like maybe not?

Code:

typedef struct PTE {
    unsigned int faddr:7;           
    unsigned int present:1;
    unsigned int wp:1;
    unsigned int mod:1;
    unsigned int ref:1;
    unsigned int pout:1;
    unsigned int fmap:1;
} PTE; 

void init_pte(PTE **pgtbl_l, int num_ps) {
// Initialize all fields to zero
    for (int i=0; i<num_ps; i++) {
        for(int j=0; j<64; j++) {
            PTE *new_pte = malloc(sizeof(PTE));
            pgtbl_l[i][j] = *new_pte;
            new_pte->faddr = 0;
            new_pte->present = 0;
            new_pte->wp = 0;
            new_pte->mod = 0;
            new_pte->ref = 0;
            new_pte->pout = 0;
            new_pte->fmap = 0;
        }
    }
}

void print_pagetable(PTE **pgtbl_l, int num_ps) {
    for (int i=0; i<num_ps; i++) {
        printf("PT[%d]: ", i);
        for (int j=0; j<64; j++) {
            printf("faddr: %d pres: %d wp: %d mod: %d ref %d", pgtbl_l[i][j].faddr,
                   pgtbl_l[i][j].present, pgtbl_l[i][j].wp, pgtbl_l[i][j].mod,
                   pgtbl_l[i][j].ref);
        }
    }
    printf("\n");
}

PTE *pgtbl_l[num_ps][64];                   
init_pte(pgtbl_l, num_ps); 
print_pagetable(pgtbl_l, num_ps);

Pointers and arrays are not the same thing. In many cases, an array decays to a pointer to its first element, however this does not flow down to multidimentional arrays.

So for a 1D array you can do this:

char A[5];
char *p = A;

But for a 2D array:

char A[5][6];
char (*p)[6] = A;

In the latter case, A is an array of size 5, where each element is an array of size 6. So the array to pointer decay happens on only the first dimension.

You need to change you function definitions to:

void init_pte(PTE pgtbl_l[][64], int num_ps) {

And:

void print_pagetable(PTE pgtbl_l[][64], int num_ps) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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