我试图通过向第一个元素添加占位符数组的大小来访问动态分配中的下一个元素。占位符数组的大小是4个字节,所以若我在地址为2147549788的第一个元素中添加4个字节,我应该查看下一个内存位置2147549792。但是,我看的是一个16字节的地址2147549804。如果我直接读取数组元素的地址,就会得到正确的地址。想知道为什么添加占位符的大小会产生不同的结果吗?
另外,如果我访问for循环外第二个元素的位置,则该位置将被另外16个字节关闭,即2147549820

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

typedef struct Section {
    int numOfStudents;
} Section;

typedef struct School {
    int schoolId;
    Section sections[1]; //placeholder
} School;

int main(void)
{
    School *schoolA_p;
    Section section1;
    int sizeOffset = 0;
    int i,sectionSize;

    int sizeOfSchool = sizeof(School) - sizeof(Section) + (sizeof(Section)*2);
    schoolA_p = (struct School *) malloc(sizeOfSchool);

    for(i=0;i<2;i++)
    {
        sectionSize = sizeof(Section);

        printf("\nsize of section = %d\n", sizeof(Section));
        printf("Number of bytes to add to first element to access the next element = %d\n", sizeOffset);
        printf("In Loop Location of schoolA_p->sections[%d]= 0x%lx\n",i, &(schoolA_p->sections[0]) + sizeOffset);

        sizeOffset += sectionSize;
    }

    printf("\n Location of schoolA_p->sections[0]= 0x%lx\n",&(schoolA_p->sections[0]));
    printf("\n Location of schoolA_p->sections[1]= 0x%lx\n",&(schoolA_p->sections[1]));

    printf("\n Outside of lopop Location of schoolA_p->sections[0]= 0x%lx\n", &(schoolA_p->sections[0])+ sizeOffset);

    free(schoolA_p);
    return 0;
}

最佳答案

指针算法的工作原理如下:如果p是指向数组元素a[n]的指针,则p + i是指向a[n + i]的指针。换句话说,指针算术以指针声明为的任何基类型的单位移动,而不是以字节为单位。

关于c - 访问动态分配数组的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32799440/

10-11 20:06
查看更多