Hello,
I have a structure and a pointer to point to this structure on the heap.
I am incrementing the pointer to add new data into the structure. After I want to display all the records in this structure. However, once the pointer has been incremented, is there a way that I can reset it to point to the first record in the structure?
My code is below:
I have a structure and a pointer to point to this structure on the heap.
I am incrementing the pointer to add new data into the structure. After I want to display all the records in this structure. However, once the pointer has been incremented, is there a way that I can reset it to point to the first record in the structure?
My code is below:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[20];
char city[20];
char state[10];
}record;
typedef record *pointerRecord;
int main(int argc, char** argv)
{
int i = 0;
//Allocate meory for 2 records
pointerRecord ptrRecord = (pointerRecord) malloc(sizeof(record[2]));
//Fill struct with data
strncpy(ptrRecord->name, "steve", sizeof(ptrRecord->name));
strncpy(ptrRecord->city, "Reading", sizeof(ptrRecord->city));
strncpy(ptrRecord->state, "Bracknell", sizeof(ptrRecord->state));
ptrRecord++;
strncpy(ptrRecord->name, "Robert", sizeof(ptrRecord->name));
strncpy(ptrRecord->city, "Tibury", sizeof(ptrRecord->city));
strncpy(ptrRecord->state, "Berks", sizeof(ptrRecord->state));
//Display contents of the structure.
//Reset pointer HERE to point to the first structure.
while(ptrRecord != 0)
{
printf("Name: %s", ptrRecord->name);
printf("City: %s", ptrRecord->city);
printf("State: %s", ptrRecord->state);
//Increment pointer HERE
}
free(ptrRecord);
getchar();
return 0;
}