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

Status
Not open for further replies.

zegulas

Traceur
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.
 
Last edited:

dheeraj_kumar

Legen-wait for it-dary!
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
 

dheeraj_kumar

Legen-wait for it-dary!
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

Right off the assembly line
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

TechFreakiez.com
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;
 
Last edited:

vandit

In the zone
@ 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.
 
Status
Not open for further replies.
Top Bottom