I have used arrays in the program; a[3] - now i want to change the program to dynamic array value

If I enter more than allocated(3) characters in the input - it throws error and the program stops running
error "Segmentation fault" (i am running c on unix)

- i dont want that to happen - it should be able to handle any number of characters entered without limit.

What should i use? i tired using
char *c1="hi" but I was not able to do it. I am a beginner level programmer.

Warm Regards
Kumar.

dynamic memory in C uses malloc(), or a similar function, to allocate dynamic memory and free() to delete dynamic memory. In C++ it's new() and delete. In either case, if you want memory for an array of items then you add the [] operator, as appropriate.

//allocate an array of 10 char using dynamic memory
char * c = malloc char[10];
char * cpp = new char[10];

Neither C nor C++ have built in array size detection. The C++ STL class do include that "technology", and for that reason alone, it may be worth your while to consider dumping arrays/C style strings and learn about the STL vector and string classes. Having said that, there isn't anything wrong with learning how to adjust your arrays so they fit "just right". Most people find it boring to do this all the time, and it's not worthwhile from a memory standpoint or a speed standpoint on most computers, but it is a reasonable learning project.

To get array sizes just right you need to somehow keep track of the current size of the array and the capacity of the array. If the size of the array equals the capacity of the array and you want to add to the array, then you need to expand the array, and if the size is less than the capacity, then you need to decrease the size of the array. You start by declaring a temporary array of the size of the current array and copy the data from the current array into the temporary array. You then delete the memory from the current array and redeclare with just the right amount of memory you want/need. Then you copy the information in the temporary array back into the original array and delete the temporary array. Here's an example using char arrays and C++. It's a bit different using other types of arrays, but the basic theory is the same.

Goal: change word to fit lakes from lake
int orig = 5;
int final = 6;
char * word = new char[orig];
strcpy(word, "lake");
char * temp = new char[orig];
strcpy(temp, word);
delete word[];
word = new char[final];
strcpy(word, temp);
word[4] = 's';
word[5] = '\0';
cout << word << endl;
delete temp[];

lerner plz use code tags

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.