Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how can to build array of string 1

Status
Not open for further replies.

ayalamite

Technical User
Sep 23, 2001
5
IL
i need to build array of string,but it the array will be dynamic when i run the program.
i will receive the number of string only in the main

thank you
 
You need to use "pointers" and the function "malloc" for doing this.
Here is an example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _maxnumber_ 50
void main()
{
char *string[_maxnumber_]; // array of pointers
int number = 0;
int i = 0;
printf(&quot;Enter the number of string that you need to memorise: &quot;);
scanf(&quot;%d&quot;,&number);
if( number > _maxnumber_ )
{
printf(&quot;This number is too big ! &quot;);
exit(0);
}
getchar();
for( i = 0; i < number; i++ )
{
printf( &quot;string %d: &quot;, i + 1 );
if( ( string = ( char* )malloc(100)) == NULL ) // allocate memory dynamically to &quot;string&quot;
{
printf(&quot;can't allocate memory. &quot;);
break;
}
gets( string );
}
printf(&quot;\nYou have entered the following strings:\n&quot;);
for( i = 0; i < number; i++ )
{
puts( string );
free( string ); // free the memory
}
}
no mather the size of the strings that you have as input,if it is less or equal to &quot;100 bytes&quot; for each string this procedure should work perfectly.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top