Правильно ли выделяется память в приведенном коде - C (СИ)
Формулировка задачи:
Прошу помощи. Вот мой код, внизу задам вопросы.
1. Что с функцией int WriteType()?? При первом вводе она работает нормально, а при втором в неё забивается пустое значение или выводится только предложение ввести число и сразу же выводится предложение о вводе следующего типа.
2. Что я сделал не так с выделением памяти? (в main() )
3. Как быть с памятью, если я допишу функцию изменения полей в программе? То есть изменение конкретного поля у конкретной строки.
#include<stdio.h> //printf,scanf,getchar
#include<conio.h> //getch,clrscr
#include<stdlib.h> //atoi,atof
struct copybook *a;
struct copybook{
int type; //square (1) or linear (0) copybooks
int pages; //amount of pages in the copybook
float price; //price of the copybook
};
struct copybook *a;
/***************************************************/
int EnterN(int minimum, int maximum);
int WriteType();
int WritePages();
float WritePrice();
void PrintListByType(struct copybook *a,int n);
void SortByPages(struct copybook *a,int n);
void SortByPrice(struct copybook *a,int n);
void PrintList(struct copybook *a,int n);
void DeleteCopybook(struct copybook * a,int n);
void deleteList(struct copybook *a);
void Menu(struct copybook *a,int n);
void MakeList(int n, struct copybook *a);
/***************************************************/
int EnterN(int minimum, int maximum){
int n;
char s[10];
char *err;
printf("BBEDUTE N>%d && <%d\n",minimum-1,maximum+1);
do{
printf("N=");
gets(s);
n=strtol(s,&err,10);
if (n>maximum||n<minimum)
*err=1;
if (*err!='\0')
printf("Error! Re-try to enter..\n");
}while(*err!='\0');
return(n);
}
void MakeList(int n, struct copybook *a){
int i;
for (i=0;i<n;i++){
printf("Enter tyoe of copybook [square (1) or linear (0) copybook:");
a[i].type=WriteType();
printf("Enter amount of pages:");
a[i].pages=WritePages();
printf("Enter the price:");
a[i].price=WritePrice();
}
}
int WriteType(){
char s[100];
int x;
char *err;
do{
gets(s);
x=strtol(s,&err,10);
if (x<0 || x>1)
*err=1;
if (*err!='\0')
printf("Error! Re-try to enter..\n");
}while(*err!='\0');
return x;
}
int WritePages(){
char s[100];
int x;
do{
scanf("%s",&s);
x=atoi(s);
if(x==0)
printf("Error! Re-try to enter..\n");
}
while(x==0);
return x;
}
float WritePrice(){
char s[100];
float x;
do{
scanf("%s",&s);
x=atof(s);
if(x==0.0)
printf("Error! Re-try to enter..\n");
}
while(x==0);
return x;
}
void PrintList(struct copybook *a,int n){
int i;
printf("Printed list:");
for (i=0;i<n;i++)
printf("\n%-2s %-6d %-5.2f$",a[i].type,a[i].pages,a[i].price$);
}
void PrintListByType(struct copybook *a,int n){
int i;
for (i=0;i<n;i++){
if(a[i].type==0)
printf("\n%-2s %-3d %-5.2f$",a[i].type,a[i].pages,a[i].price$);
}
for (i=0;i<n;i++){
if(a[i].type==1)
printf("\n%-2s %-3d %-5.2f$",a[i].type,a[i].pages,a[i].price$);
}
}
void SortByPages(struct copybook *a,int n){
int i, j;
struct copybook temp;
for (i=0;i<n;i++){
for (j=0;j<n;j++){
if (a[j].pages>a[j+1].pages){
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
printf ("List sorted by pages amount\n");
}
void SortByPrice(struct copybook *a,int n){
int i, j;
struct copybook temp;
for (i=0;i<n;i++){
for (j=0;j<n;j++){
if (a[j].price>a[j+1].price){
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
printf ("List sorted by price\n");
}
void Menu(struct copybook *a,int n){
char c;
do{
printf("\n1: Print List");
printf("\n2: Print List By Type");
printf("\n3: Print Sorted By Pages");
printf("\n4: Print Sorted By Price");
printf("\n5: ");
printf("\n6: ");
printf("\n Your choise is:");
scanf("%c",&c);
c=getchar();
switch(c){
case '1': PrintList(a,n); break;
case '2': PrintListByType(a,n); break;
case '3': SortByPages(a,n);PrintList(a,n); break;
case '4': SortByPrice(a,n);PrintList(a,n); break;
case '5': break;
case '6': break;
default: return;
}
}
while(1==1);
}
int main(){
int n;
system ("cls");
n=EnterN(1,100);
struct copybook *a;
a = (struct copybook*) malloc (sizeof(struct copybook));
MakeList(n, a);
Menu(a,n);
deleteList(a);
getch();
free (a);
}Решение задачи: «Правильно ли выделяется память в приведенном коде»
textual
Листинг программы
void flush_input(void) {
char c;
while ( scanf("%c", &c) == 1 && c != '\n' )
;
}
Объяснение кода листинга программы
- В данном коде реализована функция flush_input, которая предназначена для очистки буфера ввода.
- В функции используется цикл while, который выполняется до тех пор, пока scanf успешно считывает символ (т.е. возвращает значение 1) и этот символ не является символом новой строки '\n'.
- Внутри цикла никакие действия не выполняются, поэтому тело цикла пустое (;).
- Функция возвращает void, т.е. не возвращает никакого значения.
- В коде не происходит выделения памяти, поэтому нет необходимости проверять корректность работы с памятью.