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 take your advice seriously men.
int main()
{
int cont=0;
char *ptr;//Pointer to store characters
char c;
char choice;//Character to read (Y/N)
ptr=calloc(MAX_SIZE, sizeof(char));//Allocate at least 10 characters
if (!ptr) {//Laserlight code, finally understood EXIT_FAILURE
fprintf(stderr, "There is not enough memory.\n");
return EXIT_FAILURE;
}
do {//do while loop to work the loop at least once
printf("Insert a character: ");
scanf(" %c", &c);//I accept more efficient alternatives
ptr=realloc(ptr, MAX_SIZE * sizeof(*ptr));//re-allocate (resize) memory for character read to be stored
if (!ptr) {//Laserlight code again for re-allocating
fprintf(stderr, "La realocacion ha fallado por falta de memoria.\n");
return EXIT_FAILURE;
}
printf("Insert more characters: (Y/N)");//To insert character one by one
scanf(" %c", &choice);
ptr[cont++]=c;//Advance in the loop
} while (choice=='Y' || choice=='y');//While user press Y but also consider y, I took case sensitive in consideration
ptr[strcspn(ptr, "\n")] = '\0';//Laserlight code
printf("The characters inserted are: %s\n", ptr);
free(ptr);//Free memory at the end of the program
return 0;
}
Anny advice to make it better would be greatly appreciated. Only in C, not C++, I compiled in C and I'm working in C and I'm in C forum. Now I'm thinking, free is correctly placed? should I put another free above after calloc?
I feel like the Cristiano Ronaldo of programming . No, no, that was a joke to calm the environment.