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



## zegulas (Sep 1, 2008)

*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)

Use a linked list data structure.


----------



## zegulas (Sep 1, 2008)

I don't know how to use it, could you give an example code?


----------



## dheeraj_kumar (Sep 2, 2008)

```
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


----------



## zegulas (Sep 6, 2008)

Can someone show an example for calloc to do the same?


----------



## dheeraj_kumar (Sep 6, 2008)

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.


----------



## abhijeet.k1810 (Sep 20, 2008)

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)

use Dynamic allocation...


```
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 (Sep 21, 2008)

@ 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)

oops...ma mistake..i thought its c++ questn...


----------

