DIGIT-ARC read-only archive · snapshot: July 23, 2026

How to store n number of strings in an with unknown size

10 posts · originally from https://geek.digit.in/community/threads/how-to-store-n-number-of-strings-in-an-with-unknown-size.96890/

zegulas
zegulas Original post #1
Sep 1, 2008 at 7:03 PM
How to store n number of strings in an array with unknown size

How to declare an array for storing strings while we don't know how many will be stored, it has to be specified during runtime by the user. For C language.
QwertyManiac
Sep 1, 2008 at 8:51 PM
Use a linked list data structure.
zegulas
zegulas #3
Sep 1, 2008 at 9:13 PM
I don't know how to use it, could you give an example code?
dheeraj_kumar
Sep 2, 2008 at 1:20 PM
Code:
struct node
{
   int id;
   char *string;
   struct node *next;
}*head, *temp;
id = number of the string / index of the array
string = pointer to your string.
next = next item in linked list.
head = head of the list
temp = used to allocate new nodes in the list

you need to use the basic linked list concepts like malloc() to allocate memory, changing the next pointer etc. if you need a small tut on lists,

*cslibrary.stanford.edu/103/LinkedListBasics.pdf
*www.ehow.com/how_2056292_create-linked-list-c.html

make sure you initialize your structure members, you wouldnt want segmentation faults :D
zegulas
zegulas #5
Sep 6, 2008 at 6:44 PM
Can someone show an example for calloc to do the same?
dheeraj_kumar
Sep 6, 2008 at 7:13 PM
calloc takes in the no. of items to be assigned memory as its argument. Considering your situation, where you dont know the no. of items, its better to use malloc.
A
Sep 20, 2008 at 9:42 PM
use teh following code fragment using malloc to take inout of strings using dynamic memory allocation.
include necessary header files.
main()
{
int i=-1;
char *a,ch;
a=(char*)(malloc(a,1*sizeof(char));
printf("Enter the string");
do{
ch=getchar();
i++;
a=(char*)(realloc(a,i+1*sizeof(char));
*(a+i)=ch;
}while (ch!='\n');
*a='\0';
}
If this code has some errors please let me know i can help you out.......
Abhishek Dwivedi
Sep 20, 2008 at 10:48 PM
use Dynamic allocation...

Code:
  char *p;
  int val;
  cout<<"Enter Array size:";
  cin>>val;
  p=new char[val];
use the array as p
this is dynamic allocation of memory...remembr to delete the memory aftr ur done with ur array using delete keyword...

Code:
delete p;
vandit
vandit #9
Sep 21, 2008 at 12:43 AM
@ abhieshek

the new and delete operators are available in c++ and not c.
and the program u have written will not form a table of strings as he wants.

regarding linked lists dude it will be more convinient for u to refer some books like e balagurusamy or let us c.
Abhishek Dwivedi
Sep 21, 2008 at 11:16 AM
oops...ma mistake..i thought its c++ questn...