Creating an dynamic string array which is pointed by a const char pointer
I would like to create an array in C which dynamically grows and stores string .And would like to point that array by an pointer . How can I do it? Any suggestions will be highly appreciated.The flow of program that i want to make is as follows:
program takes input say int i =5;
create an string array of length 5
insert the string into the array.
suppose x1,x2,x3,x4,x5
and i want that array to be pointed by the const char pointer
[EDIT]
here i would like to make my problem more clear. I will take input as a number of symbols that i have to store. If i take input as 5 , then my program has to genearate five symbol and it has to be stored into array and then that array should be pointed by the pointer.
How i am approaching is:
I am 开发者_Python百科taking array of pointers. Each pointer will point to the string with two element. The first element will remain same for all. The next element in the every iteration has to increase by one and has to endup with the input i
, i had taken earlier.My problem has be storing the counter value as character.
I am not so used with C.Expecting some help.
Thanks
The idea is to use malloc
. Assume your this is your const char
pointer:
const char *string;
now you allocate as much space as you want with malloc
:
string = malloc(number_of_chars_in_the_string);
// don't forget to test that string != NULL
If this turns out to be too small, you can resize it with:
string = realloc(string, new_size);
when you're done with it, you free the memory:
free(string);
Here's an example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numElem = 0;
scanf("%d", &numElem);
printf("numElem: %d", numElem);
char *string = (char *) malloc( (numElem * sizeof(char)));
//checking of NULL here in case malloc fails
//...
//enter you chars here...
//etc...
return 0;
}
The main idea of this snippet is to use: char *string = (char *) malloc( (numElem * sizeof(char)));
to make it dynamic.
Hope this helps.
精彩评论