我試圖通過將佔位符數組的大小添加到第一個元素來訪問動態分配的下一個元素。佔位符數組的大小是4個字節,所以如果我向它的第一個元素添加4個字節,地址爲2147549788,我應該看看下一個內存位置2147549792.但是,我正在查看16字節的地址2147549804.如果我讀數組元素的地址直接得到正確的地址。想知道爲什麼添加佔位符的大小給出不同的結果? 另外,如果我訪問外部for循環第二元件的位置,該位置是關閉的另一16個字節,即2147549820訪問dynamiclly分配數組的元素
#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;
}
在回撥中,您忘記了&。 schoolA_p->分區[0] - >&schoolA_p->分區[0]。 – tstark81
@jas你可以分享你得到的o/p嗎? – Pawan
假設被遺忘的「&」是問題中的拼寫錯誤,是不是你忘記了C指針算術考慮了項目的大小?因此,p + 4步驟4 _data objects_forward,而不是4個字節。 –