This is maybe the last exercise I will do of my course (yet finished). We have 6 exercises that our instructor left in the last class, 6 exercises about memory allocation, this is the fourth one.
Statement: Insert characters through keyboard one by one; the program must ask Y/N choice to continue inserting characters (one by one). Use realloc function for memory allocation. The program must print all the characters inserted.
I have been working in the program. I am not lazy at least, you know. I tried to solve it and I'm happy, I solved it. The code works "like a charm" but I want to use the correct code according to your recommendations. Please, don't blame me too much, I promise you I am making the effort to go to the right way, but still I need more practice. I am using some code thanks to laserlight. I know there is room for improvements, that's the reason I'm posting the code here. Compiled in C Now, the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 10//No magic numbers, I took your advice seriously men
int main()
{
int cont=0;
char *ptr;//Pointer to store characters
char c;
char choice;//To read characters one by one through Y/N choice
ptr=calloc(MAX_SIZE, sizeof(char));//To allocate at least 10 characters
if (!ptr) {//Code by laserlight
fprintf(stderr, "There is not enough memory.\n");
return EXIT_FAILURE;
}
do {//do while loop to work at least once
printf("Insert a character: ");
scanf(" %c", &c);
ptr=realloc(ptr, MAX_SIZE * sizeof(char));//Expand to allow 10 extra characters
if (!ptr) {//Code by Laserlight
fprintf(stderr, "The re-allocation failed due to lack of memory.\n");
return EXIT_FAILURE;
}
printf("Insert more characters: (Y/N)");//Y/N choice to insert characters one by one
scanf(" %c", &choice);
ptr[cont++]=c;
} while (choice=='Y' || choice=='y');
ptr[strcspn(ptr, "\n")] = '\0';
printf("Characters inserted: %s\n", ptr);
free(ptr);//To free memory
return 0;
}
I have a question, should I put another free above after calloc or is ok right now? I know there is room for improvements. What do you think? I am working with C because I compiled in C and I am in C forum.
I feel the Cristiano Ronaldo of programming . No, that was a joke to relax the environment.