Array passed as parameter not accessible outside of user defined function - arrays

This code is to convert a inputted decimal number to binary, hex, and octal without format specifiers. It also is supposed to print the results to a text file. Every works fine except the 3 char arrays storing hex, oct, and binary are not accessible outside of the function that converted them.
#include <stdio.h>
#include <time.h>
char *getDateAndTime();
int getInteger();
int atoi(const char *str);
void decimalToBinary(int decValue, char binString[]);
void decimalToHex(int decValue, char hexString[]);
void decimalToOct(int decValue, char octString[]);
int saveFile(char name[], char *getDateAndTime(), int decValue, char octString[], char hexString[], char binString[]);
int main()
{
char binString[32];
char octString[32];
char hexString[32];
char dateTime[32];
char name[32];
int decValue = 0;
int saveSuccess = 0;
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
decValue = getInteger();
if (decValue != 'x'){
decimalToHex(decValue, hexString);
decimalToOct(decValue, octString);
decimalToBinary(decValue, binString);
saveFile(name, getDateAndTime, decValue, octString, hexString, binString);
}
printf("\nGoodbye!");
return 0;
}
char *getDateAndTime()
{
time_t t;
time(&t);
return ctime(&t);
}
int getInteger()
{
char number[9];
int num;
int status = 1;
do {
printf("Enter an Integer [1-1,000,000] or type x to exit: ");
fgets(number, sizeof(number), stdin);
if (number[0] == 'x')
{
status = 0;
}
else
{
num = atoi(number);
if (num < 1 || num > 1000000)
{
printf("Error: %d is out of range\n", num);
}
else
{
status = 0;
return num;
}
}
} while (status);
}
void decimalToBinary(int decValue, char binString[])
{
int quotient;
int i = 1;
int j;
quotient = decValue;
while(quotient!=0){
binString[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Decimal: %d\nBinary: ",decValue);
for(j = i -1 ;j> 0;j--)
printf("%d",binString[j]);
printf("\n");
}
void decimalToHex(int decValue, char hexString[]){
long int remainder,quotient;
int i=1,j,temp;
quotient = decValue;
while(quotient!=0){
temp = quotient % 16;
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexString[i++]= temp;
quotient = quotient / 16;
}
printf("Hexadeciaml: ");
for(j = i -1 ; j> 0; j--)
printf("%c",hexString[j]);
}
void decimalToOct(int decValue, char octString[])
{
int quotient;
int i = 1;
int j;
quotient = decValue;
while(quotient!=0){
octString[i++]= quotient % 8;
quotient = quotient / 8;
}
printf("\nOctal: ");
for(j = i -1 ;j> 0;j--)
printf("%d",octString[j]);
printf("\n");
}
int saveFile(char name[], char* getDateAndTime(), int decValue, char octString[], char hexString[], char binString[])
{
char choice;
int status = 1;
printf("Save to a file? (y/n): ");
scanf(" %c", &choice);
while (status){
if (choice == 'y'){
FILE *ptr_file;
ptr_file =fopen("G01303907_HW3.txt", "w");
if (!ptr_file){
return 1;
}
int results = fprintf(ptr_file,"Name: %s\nDate: %s\nDecimal Value:%d\nHexadecimal String: %s\nOctal String: %s\nBinary String: %s\n",name, getDateAndTime(), decValue, hexString, octString, binString);
if (results == EOF) {
printf("Error: ");
}
fclose(ptr_file);
status = 0;
return 0;
}
else if (choice == 'n')
{
status = 0;
return -1;
}
else{
printf("Error: illegal value\nSave to a file? (y/n): ");
scanf("%s", &choice);
}
}
}
terminal
Enter an Integer [1-1,000,000] or type x to exit: 23
Hexadeciaml: 17
Octal: 27
Decimal: 23
Binary: 10111
Save to a file? (y/n): y
Goodbye!
Text Document
Name: Mason
Date: Mon Oct 3 23:38:59 2022
Decimal Value:23
Hexadecimal String:
Octal String:
Binary String:

Related

Unable to read structures properly from binary

So my program creates an 2d-dynamic array of structures, reads these structures from a binary file, changes the information in the structures and writes them in the same file. The problem is, that it does not read the information from the file properly. For example, I expect the info from ptr[0][0].Flat_IDto be 101. But on the console it prints a random number, say10948144, and this jeopardizes my entire program. I tried to change the way it reads, but to no effect.
Here is my main():
#include "Header.h"
int main()
{
while(1)
{
printf("Hello world!\n");
unsigned int floors=0, flats_per_floor=0;
S_Apartament Flats;
char FileName[50];
printf("0. Exit program.\n");
printf("1. Enter a file name.\n");
printf("Please, choose a command.\n");
unsigned short choice;
scanf("%hu", &choice);
if(choice == 0)
{
break;
}
else
{
printf("Enter file name in the following format 'Name.bin' :");
scanf("%s", FileName);
}
S_Apartament **ptr = memalloc(floors, flats_per_floor, Flats, FileName);
printf("%u",ptr[0][0].Flat_ID);
while(1)
{
choice = menu();
if(choice==0)
{
break;
}
switch(choice)
{
case 1:
enterNewResidents(ptr, floors, flats_per_floor);
break;
case 2:
calculateTax(ptr, floors, flats_per_floor);
break;
case 3:
Elevator(ptr, floors, flats_per_floor);
break;
case 4:
emptyApartment(ptr, floors, flats_per_floor);
break;
default:
printf("Invalid command\n");
break;
}
writeInfo(ptr,floors,flats_per_floor, FileName);
free(ptr);
}
}
printf("Program exited successfully. Have a nice day");
return 0;
}
My header file:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
unsigned int Flat_ID;
unsigned short count_Rooms;
unsigned short count_Adults;
unsigned short count_Children;
char Family_Surname[20];
char Date[10];
float rent;
}S_Apartament;
unsigned short menu();
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50]);
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50]);
#endif // HEADER_H_INCLUDED
And my source file:
#include "Header.h"
unsigned short menu()
{
unsigned short choice=0;
printf("Welcome, to the smart House manager program! Here is a list of the available commands.\n");
printf("1. Enter new residents.\n");
printf("2. Calculate month tax.\n");
printf("3. Set elevator\n");
printf("4. Empty an apartment\n");
printf("0. Exit the program\n");
printf("Please choose a command:\n");
scanf("%hu",&choice);
return choice;
}
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50])
{
FILE *f;
f = fopen(FileName,"rb");
if(f==NULL)
{
printf("Error opening file, or no such file.");
fclose(f);
exit(1);
}
fread(&floors,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
fclose(f);
S_Apartament **arr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);
for (int i = 0; i < floors; i++)
{
arr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);
printf("Here");
}
for(int i = 0; i < floors; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
fread(&Apartment,sizeof(S_Apartament),1,f);
arr[i][j]=Apartment;
}
}
fclose(f);
return arr;
}
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short a = 0, b = 0;
printf("Enter the floor, where you wish to accommodate the new residents.\n");
scanf("%hu", &a);
printf("Good, now the flat.\n");
scanf("%hu", &b);
if((a > floors) || (b > flats_per_floor))
{
printf("Invalid coordinates.");
}
if(ptr[a-1][b-1].count_Adults==0)
{
printf("The apartment is free to use. Enter the following data:\n");
printf("Enter the number of adults\n");
scanf("%hu", &(ptr[a-1][b-1].count_Adults));
printf("Enter the number of children\n");
scanf("%hu", &(ptr[a-1][b-1].count_Children));
printf("Enter the name of the Family\n");
scanf("%s", ptr[a-1][b-1].Family_Surname);
printf("Date of entry:\n");
scanf("%s", ptr[a-1][b-1].Date);
printf("Enter the rent\n");
scanf("%f", &(ptr[a-1][b-1].rent));
}
else
{
printf("The apartment is occupied. Please, choose another one.\n");
}
}
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
int Tax = 0;
for(int i=0; i<floors; i++)
{
for(int j=0; i<flats_per_floor; j++)
{
if( (i==0) || (i==1) )
{
Tax = Tax + (3*ptr[i][j].count_Adults) + (1*ptr[i][j].count_Children);
}
else
{
Tax = Tax + (5*ptr[i][j].count_Adults) + (3*ptr[i][j].count_Children);
}
}
}
printf("Tax is: %d \n", Tax);
}
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short Elevator_location = 1;
unsigned number_of_residents = 0;
unsigned max_amount = 0;
for(int i = 1; i < floors - 1; i++)
{
for(int j = 0; j<flats_per_floor; j++)
{
number_of_residents = number_of_residents + ptr[i][j].count_Adults + ptr[i][j].count_Children + ptr[i-1][j].count_Adults + ptr[i-1][j].count_Children + ptr[i+1][j].count_Adults + ptr[i+1][j].count_Children;
}
if(number_of_residents >= max_amount)
{
max_amount = number_of_residents;
number_of_residents = 0;
Elevator_location = i + 1;
}
else
{
number_of_residents = 0;
}
}
printf("The elevator's default floor is to be set to ");
if(Elevator_location == 2)
{
printf("%hu nd floor.\n", Elevator_location);
}
else if(Elevator_location == 3)
{
printf("%hu rd floor.\n", Elevator_location);
}
else
{
printf("%hu th floor.\n", Elevator_location);
}
}
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short Entered_number = 0;
int i = 0, j = 0;
printf("Enter the number of the apartment you wish to empty:\n");
scanf("%hu", &Entered_number);
for(i=0; i<floors; i++)
{
for(j=0; j<flats_per_floor; j++)
{
if(Entered_number == ptr[i][j].Flat_ID)
{
ptr[i][j].count_Adults = 0;
ptr[i][j].count_Children = 0;
ptr[i][j].Family_Surname[0] = '\0';
ptr[i][j].rent = 0.00;
printf("Apartment is empty");
break;
}
}
if(Entered_number == ptr[i][j].Flat_ID)
{
printf("TEST");
break;
}
else if(i == (floors - 1))
{
printf("No such apartment");
}
}
}
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50])
{
FILE *fp;
fp = fopen(FileName,"wb");
if(fp==NULL)
{
printf("Error opening file");
fclose(fp);
exit(2);
}
fwrite(&floors,sizeof(unsigned),1,fp);
fwrite(&flats_per_floor,sizeof(unsigned),1,fp);
for(int i = 0; i < floors; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
fwrite(&ptr[i][j],sizeof(S_Apartament),1,fp);
}
}
fclose(fp);
}
I can think of no other way to fix this. Any help would be appretiated. Sorry for the huge amount of code.
In your memalloc and these lines you close the file
fread(&floors,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
fclose(f);
but later in your loop you try to read from it, and a few lines after this you close it again
for(int j = 0; j < flats_per_floor; j++)
{
fread(&Apartment,sizeof(S_Apartament),1,f);
arr[i][j]=Apartment;
}
Try removing the first fclose call.

malloc/struct pointer array seg fault

I have this code below, includes and other functions which are called in main are correct. But when I am trying to malloc the words[counter]->input_str, I get a segmentation fault all the time. I don't know what to do.
struct copy {
char *input_str;
char *create_word;
};
int main(int argc, char *argv[]) {
static struct copy *words[ARRAY_SIZE];
char format_str[20];
char word_str[STR_SIZE];
int how_many;
int counter = 0;
char answer;
do{
sprintf(format_str," %%%ds",STR_SIZE - 1);
printf("Enter string: ");
scanf(format_str,word_str);
words[counter]->input_str = (char *)malloc((strlen(word_str) + 1)*sizeof(char));
if(words[counter]->input_str == NULL) {
printf("memory problem\n");
exit(-1);
}
words[counter]->input_str = word_str;
printf("Enter integer: ");
scanf(" %d",&how_many);
words[counter]->create_word = duplicate(word_str,how_many);
counter++;
if(words[counter - 1] == NULL) {
printf("error\n");
exit(-1);
}
print(words,counter);
do{
printf("More (y/n)? ");
scanf(" %c",&answer);
}while(answer != 'y' && answer != 'n');
}while(counter < ARRAY_SIZE && answer == 'y');
clean(words,counter);
return(0);
}
Here are two versions of your code,one using struct copy *words[ARRAY_SIZE]; at the top of main(), the other using struct copy words[ARRAY_SIZE]; (which therefore does less memory allocation).
Array of pointers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct copy
{
char *input_str;
char *create_word;
};
enum { ARRAY_SIZE = 20, STR_SIZE = 30 };
extern char *duplicate(const char *str, int number);
extern void print(struct copy **words, int number);
extern void clean(struct copy **words, int number);
int main(void)
{
struct copy *words[ARRAY_SIZE];
char format_str[20];
char word_str[STR_SIZE];
int how_many;
int counter = 0;
char answer;
sprintf(format_str, " %%%ds", STR_SIZE - 1);
do
{
printf("Enter string: ");
if (scanf(format_str, word_str) != 1)
break;
printf("Enter integer: ");
if (scanf(" %d", &how_many) != 1 || how_many < 0 || how_many > 999)
break;
words[counter] = malloc(sizeof(*words[counter]));
words[counter]->input_str = (char *)malloc((strlen(word_str) + 1) * sizeof(char));
if (words[counter]->input_str == NULL)
{
fprintf(stderr, "memory problem\n");
exit(-1);
}
strcpy(words[counter]->input_str, word_str);
words[counter]->create_word = duplicate(word_str, how_many);
// Superfluous because duplicate exits if there is an allocation error
if (words[counter]->create_word == NULL)
{
fprintf(stderr, "error\n");
exit(-1);
}
counter++;
print(words, counter);
do
{
printf("More (y/n)? ");
if (scanf(" %c", &answer) != 1)
{
answer = 'n';
break;
}
} while (answer != 'y' && answer != 'n');
} while (counter < ARRAY_SIZE && answer == 'y');
clean(words, counter);
return(0);
}
void print(struct copy **words, int number)
{
printf("Words (%d):\n", number);
for (int i = 0; i < number; i++)
printf("[%s] => [%s]\n", words[i]->input_str, words[i]->create_word);
}
char *duplicate(const char *str, int number)
{
int len1 = strlen(str);
int len2 = number * len1 + 1;
char *space = malloc(len2);
if (space == NULL)
{
fprintf(stderr, "memory allocation failed for %d bytes\n", len2);
exit(-1);
}
for (int i = 0; i < number; i++)
strcpy(&space[i * len1], str);
space[len2 - 1] = '\0'; // In case number == 0
return space;
}
void clean(struct copy **words, int number)
{
for (int i = 0; i < number; i++)
{
free(words[i]->input_str);
free(words[i]->create_word);
free(words[i]);
words[i] = NULL;
}
}
Array of structures
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct copy
{
char *input_str;
char *create_word;
};
enum { ARRAY_SIZE = 20, STR_SIZE = 30 };
extern char *duplicate(const char *str, int number);
extern void print(struct copy *words, int number);
extern void clean(struct copy *words, int number);
int main(void)
{
struct copy words[ARRAY_SIZE];
char format_str[20];
char word_str[STR_SIZE];
int how_many;
int counter = 0;
char answer;
sprintf(format_str, " %%%ds", STR_SIZE - 1);
do
{
printf("Enter string: ");
if (scanf(format_str, word_str) != 1)
break;
words[counter].input_str = (char *)malloc((strlen(word_str) + 1) * sizeof(char));
if (words[counter].input_str == NULL)
{
fprintf(stderr, "memory problem\n");
exit(-1);
}
strcpy(words[counter].input_str, word_str);
printf("Enter integer: ");
if (scanf(" %d", &how_many) != 1 || how_many < 0 || how_many > 999)
break;
words[counter].create_word = duplicate(word_str, how_many);
// Superfluous because duplicate exits if there is an allocation error
if (words[counter].create_word == NULL)
{
fprintf(stderr, "error\n");
exit(-1);
}
counter++;
print(words, counter);
do
{
printf("More (y/n)? ");
if (scanf(" %c", &answer) != 1)
{
answer = 'n';
break;
}
} while (answer != 'y' && answer != 'n');
} while (counter < ARRAY_SIZE && answer == 'y');
clean(words, counter);
return(0);
}
void print(struct copy *words, int number)
{
printf("Words (%d):\n", number);
for (int i = 0; i < number; i++)
printf("[%s] => [%s]\n", words[i].input_str, words[i].create_word);
}
char *duplicate(const char *str, int number)
{
int len1 = strlen(str);
int len2 = number * len1 + 1;
char *space = malloc(len2);
if (space == NULL)
{
fprintf(stderr, "memory allocation failed for %d bytes\n", len2);
exit(-1);
}
for (int i = 0; i < number; i++)
strcpy(&space[i * len1], str);
space[len2 - 1] = '\0'; // In case number == 0
return space;
}
void clean(struct copy *words, int number)
{
for (int i = 0; i < number; i++)
{
free(words[i].input_str);
free(words[i].create_word);
words[i].input_str = words[i].create_word = NULL;
}
}
Sample output:
Enter string: abc
Enter integer: 1
Words (1):
[abc] => [abc]
More (y/n)? y
Enter string: def
Enter integer: 2
Words (2):
[abc] => [abc]
[def] => [defdef]
More (y/n)? y
Enter string: absolute-twaddle
Enter integer: 10
Words (3):
[abc] => [abc]
[def] => [defdef]
[absolute-twaddle] => [absolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddle]
More (y/n)? y
Enter string: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Enter integer: 0
Words (4):
[abc] => [abc]
[def] => [defdef]
[absolute-twaddle] => [absolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddleabsolute-twaddle]
[ABCDEFGHIJKLMNOPQRSTUVWXYZ] => []
More (y/n)? n
(Either program gives the same output for the same input. Both run clean under Valgrind — a site which still does not support https connections.)

How to add binary that is unsigned char type in C?

Here is the sheet that I need to follow https://imgur.com/a/JuLpQZt
Here is my code as of now
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<windows.h>
void arithmetic();
int ALU(unsigned char operand1, unsigned char operand2, unsigned char control_signals);
int askOperand1();
int askOperand2();
unsigned char operand1;
unsigned char operand2;
unsigned char control_signals;
const int ACC = 16; //ACC = ACCUMULATOR
int main()
{
for(;;)
{
system("cls");
ALU(operand2,operand2,control_signals);
}
getch();
return 0;
}
int ALU(unsigned char operand1, unsigned char operand2, unsigned char control_signals)
{
operand1=askOperand1();
operand2=askOperand2();
int pos1,pos2;
unsigned char bin8_1[] = "00000000";
unsigned char bin8_2[] = "00000000";
/*OPERAND 1*/
for (pos1 = 8; pos1 >= 0; --pos1)
{
if (operand1 % 2)
bin8_1[pos1] = '1';
operand1 /= 2;
}
printf("\n\nBinary Equivalence of Operand 1: %s",bin8_1);
/*OPERAND 2*/
for (pos2 = 8; pos2 >= 0; --pos2)
{
if (operand2 % 2)
bin8_2[pos2] = '1';
operand2 /= 2;
}
printf("\n\nBinary Equivalence of Operand 2: %s",bin8_2);
/*ARITHMETIC FUNCTIONS*/
int option, remainder = 0, sum[ACC], k;
arithmetic();
scanf("%d",&option);
switch(option)
{
case 1: //ADDITION
while (bin8_1 != 0 || bin8_2 != 0)
{
sum[k++] =(bin8_1 % 10 + bin8_2 % 10 + remainder) % 2;
remainder =(bin8_1 % 10 + bin8_2 % 10 + remainder) / 2;
bin8_1 = bin8_1 / 10;
bin8_2 = bin8_2 / 10;
}
if (remainder != 0)
sum[k++] = remainder;
--k;
printf("Sum of two binary numbers: ");
while (k >= 0)
printf("%d", sum[k--]);
break;
case 2: //SUBTRACTION VIA 2'S COMPLEMENT
break;
case 3: //MULTIPLICATION
break;
case 4: //DIVISION
break;
}
}
int askOperand1()
{
int ask1;
printf("\n\nEnter Operand 1(in decimal): ");
scanf("%d",&ask1);
if(ask1>255)
{
printf("\n\nINVALID! 0-255 ONLY! TRY AGAIN. EXITTING PROGRAM!");
getch();
exit(1);
}
return ask1;
}
int askOperand2()
{
int ask2;
printf("\nEnter Operand 2(in decimal): ");
scanf("%d",&ask2);
if(ask2>255)
{
printf("\n\nINVALID! 0-255 ONLY! TRY AGAIN. EXITTING PROGRAM!");
getch();
exit(1);
}
return ask2;
}
void arithmetic()
{
printf("\n\n");
printf("[1] ADDITION\n");
printf("[2] SUBTRACTION\n");
printf("[3] MULTIPLICATION\n");
printf("[4] DIVISION\n");
printf("\nOption: ");
}
Input has to be in decimal from 0-255 only. And then it will be converted to binary. That two binaries will be added and then print out a 16 bit output. I also don't know anything about control_signals variable and I can't ask my teacher about it because he's away for 1 week.
You declared bin8_1 and bin8_2 as unsigned char bin8_#[].
This means it's an array of unsigned char.
You're then comparing this array to an int. Try with a simple unsigned char.

Why I can't input my name with gets?

Here's the part of my code:
Problem: It skips the input of "please enter your name" to "please enter your marks"
What I tried: flushall(); _flushall(); - which worked yesterday somehow, and trying to place these functions between printf,scanf..
student *Create_Class(int size) {
int i, j;
int idStud, nameStud, markStud;
student *classStudent;
classStudent = (student*)malloc(size * sizeof(student));
for (i = 0; i < size; i++) {
classStudent[i].name = (char*)malloc(51 * sizeof(char));
int numOfmarks = 4;
printf("Please enter your name: ");
gets(classStudent[i].name);
_flushall(); //tried _flushall() and it worked yesterday.. tried fflush(NULL) too.
printf("\nPlease enter 4 marks: ");
for (j = 0; j < numOfmarks; j++) {
scanf("%d", &classStudent[i].marks[j]);
}
Avg_Mark(&classStudent[i]);
}
return classStudent;
}
EDIT: (FULL CODE)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct {
char *name;
int marks[4];
float avg;
} student;
student *Create_Class(int);
void Avg_Mark(student*);
void Print_One(student*);
void exStudents(student *s, int size);
int main() {
int size, i;
student *arr;
printf("\nEnter the number of students: \n");
scanf("%d", &size);
arr = Create_Class(size);
exStudents(arr, size);
for (i = 0; i < size; i++)
free(arr[i].name);
free(arr);
getch();
}
student *Create_Class(int size) {
int i, j;
int idStud, nameStud, markStud;
student *classStudent;
classStudent = (student*)malloc(size * sizeof(student));
for (i = 0; i < size; i++) {
classStudent[i].name = (char*)malloc(51 * sizeof(char));
int numOfmarks = 4;
int sizeOfName;
printf("Please enter your name: \n");
_flushall();
fgets(classStudent[i].name,50,stdin);
sizeOfName = strlen(classStudent[i].name);
printf("Please enter 4 marks: ");
for (j = 0; j < numOfmarks; j++) {
scanf("%d", &classStudent[i].marks[j]);
}
Avg_Mark(&classStudent[i]);
}
return classStudent;
}
void Avg_Mark(student *s) {
int i, numOfMarks = 4, sum = 0;
for (i = 0; i < numOfMarks; i++) {
sum += s->marks[i];
}
s->avg = (sum / 4.0);
}
void Print_One(student *s) {
printf("The average of %s is %f", s->name, s->avg);
}
void exStudents(student *s, int size) {
int flag = 1;
while (size > 0) {
if (s->avg > 85) {
Print_One(s);
flag = 0;
}
s++;
size--;
}
if (flag)
printf("\n There're no students with above 85 average.");
}
As you have already been told in comments, the solution is to use a two-step approach: Read lines first, then scan these lines as appropriate. This reflects how users are going to answer your prompts, namely by providing the information and then hitting enter.
Here's a variant of your code which does that. I've also changed the main function, because it also used scanf and I've added a function to strip white space from the string input by fgets. (This function requires the <ctype.h> header.)
#include <ctype.h>
int main()
{
char line[80];
int size, i;
puts("Enter the number of students:");
if (fgets(line, sizeof(line), stdin) == NULL) exit(1);
if (sscanf(line, "%d", &size) == 1 && size > 0) {
student *arr = Create_Class(size);
exStudents(arr, size);
for (i = 0; i < size; i++) free(arr[i].name);
free(arr);
}
return 0;
}
/*
* strip white space from beginning and end of string
*/
char *strip(char *str)
{
size_t l = strlen(str);
while (l > 0 && isspace((unsigned char) str[l - 1])) l--;
str[l] = '\0';
while (isspace((unsigned char) *str)) str++;
return str;
}
/*
* Create students and prompt user for input
*/
student *Create_Class(int size)
{
int i;
student *classStudent = malloc(size * sizeof(student));
for (i = 0; i < size; i++) {
char line[80];
char *p;
int okay = 0;
puts("Please enter your name:");
if (fgets(line, sizeof(line), stdin) == NULL) exit(1);
p = strip(line);
classStudent[i].name = malloc(strlen(p) + 1);
strcpy(classStudent[i].name, p);
while (!okay) {
int j = 0;
okay = 1;
puts("Please enter 4 marks:");
if (fgets(line, sizeof(line), stdin) == NULL) exit(1);
p = line;
while (p && j < 4) {
char *tail;
int m = strtol(p, &tail, 10);
if (p == tail) break;
if (m < 1 || m > 100) {
puts("Illegal mark.");
okay = 0;
}
classStudent[i].marks[j++] = m;
p = tail;
}
if (j < 4) {
printf("Expected 4 marks, but got %d.\n", j);
okay = 0;
}
}
Avg_Mark(&classStudent[i]);
}
return classStudent;
}
Please refrain from flushing buffers wihout reason. When a new-line character is written, stdout is flushed, so make it a rule to terminate all your strings with a new-line. New-lines at the beginning of strings instead of at the end are a sign of untidy output.
SOLUTION:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct { //struct decleration
char *name;
int marks[4];
float avg;
} student;
//functions decleration
student *Create_Class(int);
void Avg_Mark(student*);
void Print_One(student*);
void exStudents(student *s, int size);
int main() {
/*variable declerations*/
int i, size;
char line[80];
student *arr;
/*Input number of students*/
printf("\nEnter the number of students: \n");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &size);
/*Get name of students, marks, and calculate average above 85*/
arr = Create_Class(size);
exStudents(arr, size);
/*Free memory*/
for (i = 0; i < size; i++)
free(arr[i].name);
free(arr);
getch();
}
student *Create_Class(int size) { /*Get names of each student, and their 4 marks.*/
/*Variable declerations*/
int i, j;
char line[51];
student *classStudent;
/*Dynamic allocation to assign structure to every student*/
classStudent = (student*)malloc(size * sizeof(student));
/*Get name of students and their 4 marks*/
for (i = 0; i < size; i++) {
/*Variable decleration and dynamic allocation of 51 chars*/
classStudent[i].name = (char*)malloc(51 * sizeof(char));
int numOfmarks = 4;
int sizeOfName;
/*Input name of student*/
printf("Please enter your name: \n");
scanf("%s", classStudent[i].name);
/*Input marks of student*/
printf("Please enter 4 marks: ");
for (j = 0; j < numOfmarks; j++) {
scanf("%d", &classStudent[i].marks[j]);
}
/*Calculate average, and print averages of students above 85*/
Avg_Mark(&classStudent[i]);
}
return classStudent;
}
/*Calculate averages of students*/
void Avg_Mark(student *s) {
int i, numOfMarks = 4, sum = 0;
for (i = 0; i < numOfMarks; i++) {
sum += s->marks[i];
}
s->avg = (sum / 4.0);
}
/*Print average (if bigger than 85)*/
void Print_One(student *s) {
printf("The average of %s is %0.1f\n", s->name, s->avg);
}
/*Check whether the average is bigger than 85*/
void exStudents(student *s, int size) {
int flag = 1; //flag to check if there are any students with avg above 85
while (size > 0) {
if (s->avg > 85) {
Print_One(s); //Print the average
flag = 0; //We found atleast one student with avg > 85
}
s++; //Advance to next student
size--;
}
if (flag)
printf("\n There're no students with above 85 average.");
}
The problem in your code is that scanf does not consume the new-line returned by the user in:
scanf("%d", &size);
So when the program reaches:
fgets(classStudent[i].name,50,stdin);
the remaining new-line in stdin is received before the user can type anything.
A solution is to replace the initial scanf call by fgets and atoi calls.
char size_str[5];
fgets(size_str,5,stdin);
size = atoi(size_str);
A combination of fgets and sscanf also works also fine in general to first process user inputs and then convert it.
The variant with sscanf is:
char size_str[5];
fgets(size_str,5,stdin);
sscanf(size_str,"%d\n",&size);
Note that it might be safe to stop the program if the value entered is too large. Here we allow from 0 up to 999.
Note also that you have to do the same change some lines below.
instead of:
scanf("%d", &classStudent[i].marks[j]);
write:
char mark_str[5];
fgets(mark_str,5,stdin);
sscanf(mark_str,"%d\n",&classStudent[i].marks[j]);
Hope this helps.

Decimal to binary algorithm in C

I am trying to use the following algorithm to convert a decimal number to a binary number in C. I don't understand why it doesn't work properly for some inputs (e.g. for 1993 I get 1420076519).
int aux=x;
long bin=0;
while (aux>0)
{
bin=bin*10+aux%2;
aux=aux/2;
}
printf("%d in decimal is %ld in binary.", x, bin);
When you print a long you dont print the binary. The best way to convert to binary or show the binary representation of a decimal number is by storing it in a string. Bellow is a solution offered in a another SO answer
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
If you know the algorithm there's no reason not to use itoa
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int n;
char output[100];
printf("Enter a number: ");
scanf("%d", &n);
itoa(n, output, 2); //2 means base two, you can put any other number here
printf("The number %d is %s in binary.", n, output);
return 0;
}
How does the conversion works?
/* Example:
125(10) -----> ?(2) 125 |_2
-1- 62 |_2
-0- 31 |_2
-1- 15 |_2
-1- 7 |_2
-1- 3 |_2
-1- 1 */
So in this example the binary number for 125(10) is 1111101(2), and this is the process I describe in my function.
/* Functions declaration (Prototype) */
int wordCalculator( int * const word, long int number, int base );
int main( void )
{
int i, base;
int word[ 32 ];
unsigned long int number;
printf( "Enter the decimal number to be converted: " );
scanf( "%ld", &number );
printf( "\nEnter the new base: " );
scanf( "%d", &base );
i = wordCalculator( word, number, base );
printf( "The number is: " );
for(; i >= 0; i--){
if ( word[ i ] <= 9)
printf( "%d", word[ i ] );
else
/* 65 represents A in ASCII code. */
printf( "%c", ( 65 - 10 + word[ i ] ) );
}
printf( "\n" );
}
int wordCalculator( int * const word, long int number, int base )
{
unsigned long int result = number;
int i, difference;
i = 0;
do{
difference = result % base;
result /= base;
*( word + i ) = difference;
i++;
if ( result < base )
*( word + i ) = result;
} while( result >= base );
return i;
}
I think the shortest answer is
char* getBinary(int n,char *s)
{
while(n>0)
{
*s=(n&1)+'0';
s++;
n>>=1;
}
*s='\0';
return s;
}
In the called function print it in reverse way .. because storing is done LSB to MSB
But we have to print MSB first then LSB
You should be using strings to store binary number. Following code should work for you.
#include <stdio.h>
#include <stdlib.h>
char *decimal_to_binary(int);
main()
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number system\n");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %s\n", n, pointer);
free(pointer);
return 0;
}
char *decimal_to_binary(int n)
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if ( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 31 ; c >= 0 ; c-- )
{
d = n >> c;
if ( d & 1 )
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '\0';
return pointer;
}
You can use the below algorithm to convert Decimal number to Binary number system.
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
binary = (rem * place) + binary;
tempDecimal /= 2;
place *= 10;
}
printf("\nDecimal number = %lld\n", decimal);
printf("Binary number = %lld", binary);
return 0;
}
This is a recursive solution that i wrote, it is simple and works fine.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int printBinary(int N)
{
if(N < 0){errno = EINVAL; return -1;}
if(N == 0)
printf("0");
else if(N == 1)
printf("1");
else
{
printBinary(N/2);
printf("%d", N%2);
}
return 0;
}
int main(int argc, char* argv[])
{
if(argc < 2)
{
fprintf(stderr, "usage: %s NUM\nWhere NUM is an integer number\n", argv[0]);
exit(EXIT_FAILURE);
}
errno = 0;
long NUM = strtol(argv[1], NULL, 10);
if(NUM == 0 && errno != 0)
{
perror("Error during number acquisition: ");
exit(EXIT_FAILURE);
}
if(NUM < 0)
{
printf("-");
printBinary(-NUM);
}
else
printBinary(NUM);
printf("\n");
return 0;
}

Resources