How to allocate initial memory,and increase memory in each user input for a array of strings which that number of columns are known. for example: ` char* type[20]; I want to allocate initial memory for it and increase space for each scanf("%s", type[i]); which is in the loop. could you please help Me
3 Answers
You can use dynamic memory allocation for that
char *read_string(void)
{
int c;
int i = 0;
char *s = malloc(1);
printf("Enter a string: \t"); // It can be of any length
/* Read characters until found an EOF or newline character. */
while((c = getchar()) != '\n' && c != EOF)
{
s[i++] = c;
s = realloc(s, i+1); // Add memory space for another character to be read.
}
s[i] = '\0'; // Nul terminate the string
return s;
}
int main(void)
{
char* type[20];
for( size_t i = 0; i < sizeof(type); i++)
type[i] = read_string();
// Do some other stuff
}
Do not forget to free memory when you are done with it.
Comments
an array is a a contiguous block of memory, when you declare an array of a certain type, you can no longer increase or decrease its size.
one approach would be for you to declare a reasonable large sized array of char to hold your "string". like this:
const int size=256;
char input[size]; //declares an array of 256 chars
as for inputting actual "strings" in the arary of char, you COULD use scanf but I recommend you use fgets because it is much safer.
while(fgets(input, size, stdin)!=NULL)
{
//do something with input
}
This approach is susceptible to buffer overflow and is not necessarily safe, but is common approach nonetheless
as for your "array of string" problem, you want to allocate everything dynamically. ( if you dynamically allocate a char** and make it point to stack allocated char[] you are asking for big time trouble)
you should use a default size for your char** (say to take in 1000 char* ) and use a default allocation size for each of your char* ,for example 256 *sizeof(char) bytes.
this way you can use realloc every time you exhaust your space.
Comments
You can use standard function realloc declared in header <stdlib.h> each time when a new string has to be read.
Here a demonstrative program that instead of reading strings just copies a fixed number of them
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main( void )
{
char ( *s )[20] = NULL;
char ( *p )[20] = NULL;
size_t n = 0;
do
{
p = realloc( s, ( n + 1 ) * sizeof( *s ) );
if ( p )
{
s = p;
strcpy( s[n], ( char[] ){ 'A' + n, '\0'} );
++n;
}
} while ( p && n < 10 );
for ( size_t i = 0; i < n; i++ ) puts( s[i] );
free( s );
}
The program output is
A
B
C
D
E
F
G
H
I
J
Pay attention to how the function realloc is used.
If you know that the number of strings can not be less than some constant then you can initially allocate dynamically an array of the size that is equal to this constant.
For example
#define MIN_SIZE 10
//...
char ( *s )[20] = malloc( MIN_SIZE * sizeof( *s ) );
realloc.