Frank said:
That's just it. I need to iterate through the array to display the
elements. I tried to use the array directly, but that doesn't seem to work.
It goes on forever.
typedef struct screen_disp
{
int sd_row;
int sd_col;
char *sd_buff;
} SCR_DISP;
void quick_screen(SCR_DISP *display_scr)
{
while (display_scr)
{
gotoxy(display_scr->sd_col, display_scr->sd_row);
printf("ROW:%d COL:%d Buff:[%s]",
display_scr->sd_row,
display_scr->sd_col,
display_scr->sd_buff);
display_scr++;
}
return;
}
There are several ways you can tackle this problem. One way is
to do as your original post; use a NULL. I favor to enclose an array
of the struct pointers which keeps changing in elements along
with a variable that keeps count of the current count. Then you
write functions that passes a pointer of this datatype ot functions
that will manipulate it. These functions can use the count variable
to determine the size of the array if it is needed.
Example:
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#define STRS_SZ 16
typedef struct screen_disp
{
int sd_row;
int sd_col;
char sd_buff[STRS_SZ];
} SCR_DISP;
typedef struct SCR_DISP_ARR
{
SCR_DISP **disp;
size_t cnt;
} SCR_DISP_ARR;
typedef int (*CMP)(const void *v1, const void *v2);
int AddSCR_DISP_ARR(SCR_DISP_ARR *p, int row, int col,
const char *buff);
void FreeSCR_DISP_ARR(SCR_DISP_ARR *p);
void SortSCR_DISP_ARR(SCR_DISP_ARR *p,CMP cmp);
void PrintSCR_DISP_ARR(SCR_DISP_ARR *p);
int cmp_buff(const void *v1, const void *v2);
int main(void)
{
SCR_DISP_ARR test = {NULL};
AddSCR_DISP_ARR(&test,3,5,"Gamma");
AddSCR_DISP_ARR(&test, 5,7,"Alpha");
AddSCR_DISP_ARR(&test,7,9,"Beta");
puts("\t\tEXAMPLE OF SORTING BY AN ARRAY OF POINTERS\n");
puts("\tThe array unsorted:");
PrintSCR_DISP_ARR(&test);
puts("\n\tThe array sorted by buff:");
SortSCR_DISP_ARR(&test,cmp_buff);
PrintSCR_DISP_ARR(&test);
FreeSCR_DISP_ARR(&test);
return 0;
}
int AddSCR_DISP_ARR(SCR_DISP_ARR *p, int row, int col,
const char *buff)
{
SCR_DISP **tmpp;
if((tmpp = realloc(p->disp,(p->cnt+1)*sizeof *tmpp)) == NULL)
return 0;
if((tmpp[p->cnt] = malloc(sizeof **tmpp)) == NULL)
return 0;
p->disp = tmpp;
strncpy(p->disp[p->cnt]->sd_buff,buff,STRS_SZ);
p->disp[p->cnt]->sd_buff[STRS_SZ-1] = '0';
p->disp[p->cnt]->sd_row = row;
p->disp[p->cnt++]->sd_col = col;
return 1;
}
void FreeSCR_DISP_ARR(SCR_DISP_ARR *p)
{
size_t i;
for(i = 0;i < p->cnt;i++)
free(p->disp
);
free(p->disp);
p->disp = NULL;
p->cnt = 0;
return;
}
void SortSCR_DISP_ARR(SCR_DISP_ARR *p,CMP cmp)
{
qsort(p->disp,p->cnt,sizeof *p->disp,cmp);
return;
}
void PrintSCR_DISP_ARR(SCR_DISP_ARR *p)
{
size_t i;
for( i = 0; i < p->cnt;i++)
printf("%d) row: %d col: %d buff: \"%s\"\n",
i+1,p->disp->sd_row,p->disp->sd_col,
p->disp->sd_buff);
return;
}
int cmp_buff(const void *v1, const void *v2)
{
SCR_DISP * const*e1 = (SCR_DISP * const*)v1;
SCR_DISP * const*e2 = (SCR_DISP * const*)v2;
return strcmp((*e1)->sd_buff,(*e2)->sd_buff);
}