Предположим, что следующая программа имеет множество структур, используемых для хранения (здесь их только 2), и одна структура используется для обработки структур хранения.
Структуры структуры1 и структуры2 являются структурами хранения и различаются по размеру. Эти структуры хранятся последовательно в памяти, и структура mainStructure перемещается по памяти для обработки каждой структуры.
Структуры структуры1 и структуры2 различаются по размеру, и они могут храниться во фрагменте памяти в любом порядке.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char attr1[30];
int attr2;
float attr3;
} structure1;
typedef struct
{
short attr4;
short attr5[5];
char attr6[40];
} structure2;
typedef struct
{
char *headPointer;
int mainStructureAttr1;
char nameOfStruct[28];
char *structPointer;
} mainStructure;
int main(void)
{
structure1 s1a = { "Hello From Structure 1 a.", 1, 3.14159f};
structure1 s1b = { "Hello From Structure 1 b.", 2, 9.87654f};
structure2 s2a = {"Hello From Structure 2", 3, 5.6789f};
mainStructure mainS = {"\0", 101, "Hello From Main Structure.", "\0"};
//Allocate a chunk of memory to store all the data.
mainS.structPointer = (char*)calloc(3, 100);//total 300
///1st structure inserted into memory
memcpy(mainS.structPointer, &s1a, sizeof(structure1));
//set headPointer to the start of the memory
mainS.headPointer = mainS.structPointer;
//Move the tracking pointer to the next part of memory.
mainS.structPointer += sizeof(structure1);
///2nd structure inserted into memory
memcpy(mainS.structPointer, &s2a, sizeof(structure2));
//Move the tracking pointer to the next part of memory.
mainS.structPointer += sizeof(structure2);
///3rd structure inserted into memory
memcpy(mainS.structPointer, &s1b, sizeof(structure1));
dumpMemory(mainS);
printf("Done \n");
return 0;
}
void dumpMemory(mainStructure mainS)
{
printf ("=====Start Memory Dump=====\n");
printf ("%s", mainS.headPointer);
printf ("\n=====End Memory Dump=====\n");
}
Структура mainStructure использует один указатель для перемещения по памяти и другую точку, которая указывает на начало структуры памяти.
Как я могу использовать указатель, который ссылается на этот большой кусок памяти и выгружает все это. Приведенный выше код пытается это сделать, но поскольку используется% s, он останавливается на первых 0.
Представьте, что dumpMemory () является частью некоторой внешней библиотеки, и его единственная цель - сбросить часть памяти.
Как можно закодировать dumpMemory (), чтобы он выгружал всю память, на которую указывает headPointer, что является началом памяти со всеми структурированными данными?