NO

Author Topic: simple string list  (Read 2951 times)

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
simple string list
« on: August 04, 2017, 11:03:33 AM »
Code: [Select]
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct _STRLIST {
int size;
char str[];
}STRLIST,*PSTRLIST;

#define BLOCKSIZE 10

STRLIST *strlist_init(int size)
{
STRLIST *slist = malloc(size); // name buffer
slist->size = size; // alloc size for checking
return slist;
}

int strlist_insert_string(STRLIST *strlist, char *str)
{
STRLIST *sl = (STRLIST*)((unsigned char*)strlist+sizeof(int));
int len = strlen(str);
while (sl->size > 0 && sl->str) { // find first free space
//printf("sl %p sl->size %d sl->str '%s'\n", sl, sl->size, sl->str);
if ((sl-strlist+len) > strlist->size) {
int llen = (unsigned char*)sl-(unsigned char*)strlist;
strlist = realloc(strlist, BLOCKSIZE); // pointer can move ?
strlist->size += BLOCKSIZE;
sl = (STRLIST*)((unsigned char*)strlist+sizeof(int)); // refresh pointer
unsigned char* p = (unsigned char*)sl;
*(int*)(p+llen+len) = 0; // zero next size
}
if (!strcmp(str, sl->str))
return (unsigned char*)sl-(unsigned char*)strlist;
sl = (STRLIST*)(sl->size + sizeof(int)+(unsigned char*)sl+1); // move to next block
}
sl->size = len;
strcpy(sl->str, str);
*(int*)(sl->str+len) = 0; // zero next size
return (unsigned char*)sl-(unsigned char*)strlist;
}

STRLIST *strlist_first(STRLIST *slist)
{
return (STRLIST*)((unsigned char*)slist+sizeof(int)); // init start
}

STRLIST *strlist_next(STRLIST *sl)
{
return (STRLIST*)((unsigned char*)sl + sl->size + sizeof(int)+1); // move to next block
}

int __cdecl main(void)
{
STRLIST *flist = strlist_init(10);
STRLIST *fl = (STRLIST*)((unsigned char*)flist+sizeof(int)+1);
int pos;
printf("flist=%p\n", flist);
pos = strlist_insert_string(flist, "test1.c"); // first file
printf("pos=%d\n", pos);
pos = strlist_insert_string(flist, "test2.c"); // second file
printf("pos=%d\n", pos);
pos = strlist_insert_string(flist, "test1.c"); // try duplicate
printf("pos=%d\n", pos);
pos = strlist_insert_string(flist, "test3.c"); // another file
printf("pos=%d\n", pos);

for (int i=0; i<10; i++) {
char buf[20];
sprintf(buf, "test%d.c", i);
pos = strlist_insert_string(flist, buf);
printf("pos=%d\n", pos);
}

fl = strlist_first(flist); // move to first string
while (fl->size > 0 && fl->str) { // traverse string list
printf("size %d str '%s'\n", fl->size, fl->str);
fl = strlist_next(fl); // move to next string
}
return 0;
}
Let me know about possible errors.
May the source be with you