In this post I show you how to implement a list(static) of string without using memory allocation

 
#define MAXCOL 50
#define MAXROW 15
 typedef struct {
  char Content[MAXCOL];
} ListolS;
ListolS Ls[MAXROW];

/*Init List*/
char ListOfSInit()
{
   memset(Ls,0,sizeof(Ls));
   return 1;
}

/*
    return -1 list is full
           >-1 disponible index
*/
int ListOfSReadFreeIndex()
{
    int bret=-1,index=0;
    while(index-1)
    {
        memcpy(Ls[m].Content,s,strlen(s));
        bret=m;
    }
    return bret;
}
/*  INPUT : index of item to read
    OUTPUT: s item string
    return -2 out of range
           -1 empty item
          >=0 echo index */
int ListOfSReadListIndex(int index,char *s)
{
    int bret=-2;
    if (index<MAXROW)
    {
        if(Ls[index].Content[0]>0)
        {
           strcpy(s,Ls[index].Content);
           bret=index;
        }
        else
           bret=-1;
    }
    return bret;
}

/*  INPUT : index to remove
    return -1 out of range, otherwise index removed

                       */
int ListOfSRemoveContentAt(int index)
{
    int bret=-1;
    if (index<MAXROW)
    {
        //shift memory and clear last item
        memcpy(&Ls[index],&Ls[index+1],sizeof(ListolS)*(MAXROW-index-1));
        memset(&Ls[MAXROW-1],0,sizeof(ListolS));
        bret=index;
    }
    return bret;
}

How to use it.

 
void testofList()
{
    char s[MAXCOL],j;
    int index=-1;
    ListOfSInit();

    //populate list of string
    for (j=0;j<MAXROW;j++)
    {
        sprintf(s,"this is item %3d",j);
        index=ListOfSAdd(s);

    }

    printf("********** Print List **********\n");
    for (j=0;j<MAXROW;j++)
    {
        ListOfSReadListIndex(j,s);
        printf("index %3d %s\n",j,s);
    }
    printf("\n********** Remove three item **********\n");
    ListOfSRemoveContentAt(2);
    ListOfSRemoveContentAt(2);
    ListOfSRemoveContentAt(2);

    printf("\n********** RePrint LIst **********\n");
    for (j=0;j-1)
           printf("Index %3d %s\n",j,s);
    }
}

Output Console windows
Cattura

See also:List of Queue and List Of Dictionary

Advertisements