typedef struct {
char * fname;
char * lname;
} single_entry;
I'm going through an exercise where we can't use:
single_entry * next;
To create a linked list.
How can I accomplish the same thing without using a linked list? I'm thinking making another struct like this?
typedef struct {
single_entry * next;
} myEntry;
How would I use this though? I'm so familiar with everything just in one struct.
typedef struct
{
char *fname;
char *lname;
} single_entry;
typedef struct
{
single_entry *array;
unsigned size, capacity;
} se_array;
void initialise(se_array *sarray)
{
sarray->size = 0;
sarray->capacity = 0;
}
void add_to_array(se_array *sarray, single_entry entry)
{
if(sarray->capacity == 0)
{
sarray->array = malloc(sizeof(single_entry) * (sarray->capacity = 3));
sarray->array[sarray->size++] = entry;
}
else if(sarray->capacity == sarray->size)
{
sarray->array = realloc(sarray->array, sizeof(single_entry) * (sarray->capacity *= 1.5));
sarray->array[sarray->size++] = entry;
}
else
{
sarray->array[sarray->size++] = entry;
}
}
int main(void)
{
se_array my_array;
initialise(&my_array);
single_entry my_entry;
strcpy(my_entry.fname, "first");
strcpy(my_entry.lname, "last");
add_to_array(&my_array, my_entry);
my_array.array[0].fname; // element 0 fname
}
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.