Originally Posted by
CommonTater
Well yes you can and no you can't... There's a lot of overhead in your method...
This gives you space for 100 strings, each of which can be 20 characters long.
When working with strings, it behaves like a single dimensional array...
Code:
printf("%s", word[31]);
is perfectly legit and will work...
but it's far easier to use than trying to stack strings up in a unidimensional array and uses the same amount of memory.
I guess something like this would have been my approach - basically this is based on an unidimensional array
Code:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef char STRING[20];
typedef struct mystringstore
{
struct mystringstore *first;
struct mystringstore *next;
struct mystringstore *prev;
size_t free;
size_t space;
char text[1];
}mystringstore;
mystringstore *init_sstore(size_t datasize);
int addin_sstore(mystringstore *_this,STRING tmpstr,unsigned int tmplen);
void destroy_sstore(mystringstore **store);
int main()
{
int rval;
STRING tmp;
mystringstore *store=init_sstore(100);
if(NULL==store)
{
perror("sstore init failed!\n");
return -1;
}
for(;;)
{
unsigned int tmplen;
printf("givemeword or quit to quit\n");
if(NULL==fgets(tmp,20,stdin))
{
/* User gave EOF */
break;
}
tmplen=strlen(tmp);
if('\n' == tmp[tmplen-1])
{
tmplen--;
if(tmp[tmplen-1]=='\r')
tmplen--;
}
if(4==tmplen)
{
if( *((int32_t *)"quit")==*((int32_t *)tmp))
{
/* quit */
break;
}
}
if((rval=addin_sstore(store,tmp,tmplen)))
{
perror("Mysterious error\n");
return -1;
}
}
return 0;
}
mystringstore* additem_sstore(mystringstore *_this)
{
mystringstore* _new=init_sstore(_this->space);
if(NULL==_new)
{
printf("Failed to add new store item!\n");
}
else
{
_new->first=_this;
_new->prev=_this;
while(NULL!=_new->prev->next)
_new->prev=_new->prev->next;
_new->prev->next=_new;
}
return _new;
}
int addin_sstore(mystringstore *_this,STRING tmpstr,unsigned int tmplen)
{
mystringstore *curr;
if(NULL==_this)
{
printf("ASSERT: Uninitialized store? %s:%d\n", __FILE__,__LINE__);
return -1;
}
if(tmplen>=_this->space)
{
printf("Cannot store %u bytes, store is only %u bytes\n",tmplen,_this->space);
return -1;
}
curr=_this;
while(NULL!=curr)
{
if(curr->free>tmplen)
{
break;
}
curr=curr->next;
}
if(NULL==curr)
{
curr=additem_sstore(_this);
if(NULL==curr)
{
return -1;
}
}
memcpy(&(curr->text[curr->space-curr->free]),tmpstr,tmplen);
curr->free-=(tmplen+1);
return 0;
}
mystringstore *init_sstore(size_t datasize)
{
mystringstore *_this=calloc(1,sizeof(mystringstore)+datasize-1);
if(NULL!=_this)
{
memset(_this,0,datasize);
}
_this->space=datasize;
_this->free=datasize;
return _this;
}
void destroy_sstore(mystringstore **store)
{
if(NULL!=store && NULL != *store)
{
free(*store);
*store=NULL;
}
}