I'm trying to write a program that allows to add data about different types of stars and print them back on the screen. Why does this not work:
typedef union{
struct{
char name_main[30];
int age;
char color[12];
};
struct{
char name_binary[30];
double radius_1, radius_2;
};
struct{
char name_light[30];
double luminosity_low, luminosity_high, period;
};
}STARS;
int main(int argc, char **argv)
{
bool running = true;
int choice;
STARS *star = (STARS *)malloc(sizeof(star));
printf("Star Menu\n");
putchar('\n');
while(running)
{
putchar('\n');
printf("Please choose a type of star:\n");
printf("1. Main Sequence Star\n2. Binary Star\n3. Variable Light Star\n4. Exit\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("You've chosen: Main Sequence Star\n");
printf("Please enter the name of the star:\n");
scanf("%s", star->name_main);
//printf("%s", star->name_main);
printf("Please enter the age of: %s\n", star->name_main);
scanf("%d", &star->age);
printf("Age: %d\n", star->age);
printf("Please enter the color of: %s\n", star->name_main);
scanf(" %s", star->color);
printf("Color: %s\n", star->color);
// printf("Type : Main sequence | Name : %s | Age : %d | Color : %s\n", star->name_main, star->age, star->color);
break;
case 2:
printf("You've chosen: Binary Star\n");
printf("Please enter the name of the star:\n");
scanf("%s", star->name_binary);
printf("Name: %s\n", star->name_binary);
printf("The radius of the first star:\n");
scanf("%lf", &star->radius_1);
printf("The radius of the second star:\n");
scanf("%lf", &star->radius_2);
printf("Radius 1: %.2lf | Radius 2: %.2lf\n", star->radius_1, star->radius_2);
break;
case 3:
printf("You've chosen: Variable Light Star\n");
break;
case 4:
printf("Exit\n");
running = false;
break;
}
}
return 0;
}
I'm using a union of structs because each star has specific characteristics and we don't care about the others' when we write for a certain type. The issue appears at the color, if I write red the output will be: Color: r:. I've tried adding a space before the format specifier, consuming a character before using scanf but the issue persists and I'm not sure why. Any thoughts?
You didn't allocate enough size of buffer. sizeof(star) is the size of the pointer. A pointer is typically 4-byte or 8-byte long, but the structure is at least 30-byte long for char name_main[30];.
Also note that casting results of malloc() family is considered as a bad practice.
Wrong line:
STARS *star = (STARS *)malloc(sizeof(star));
It should be:
STARS *star = malloc(sizeof(*star));
STARS *star = (STARS *)malloc(sizeof(star));
It's a mistake. sizeof(star) returns size of the pointer, not the structure.
Change it to: STARS *star = (STARS *)malloc(sizeof(*star)); to fix your problem.
Related
I'm new to C, and currently trying to practice on some simple codes, and I'm currently stuck with that next one.
After entering the first customer data, and repeat the code... View_customer function fails to show the saved data, and when I try to go to enter a second account data, it fails at the second entry.
#include<stdio.h>
#include<stdlib.h>
typedef struct cust{
char name[60];
int acc_no,age;
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
} cust;
void new_account(int num);
void view_account(int num);
int main()
{
cust customers[10];
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
do{
printf("\n How can we serve you today? \n 1.Create a new account \n 2.Print an existing Account info \n ");
scanf("%d",&n);
if (n==1)
{
new_account(cutomer_number);
cutomer_number++;
}else {
printf("Please enter your Cust number: ");
scanf(" %d",&cutomer_num2);
view_account(cutomer_num2);
};
printf("\n Press Y to continue. Press any Key To Exit: ");
scanf(" %c",&answer);
}while (answer == 'Y' || answer == 'y');
return 0;
}
void view_account(int n)
{
cust customers[n];
printf("Your name is %s \n ", customers[n].name);
printf("Your age is %d \n", customers[n].age);
printf("Your address is %s \n", customers[n].address);
printf("Your citizenship is %s \n", customers[n].citizenship);
printf("Your phone number is %f \n", customers[n].phone);
printf("Your account type is %s \n", customers[n].acc_type);
};
void new_account(int n)
{
cust customers[n];
customers[n].acc_no = n;
printf("You are the customer number %d \n", customers[n].acc_no);
printf("Please, Enter your name: ");
scanf("%s", &customers[n].name);
printf("Please, Enter your age:");
scanf(" %d", &customers[n].age);
printf("Please, Enter your address: ");
scanf(" %s", &customers[n].address);
printf("Please, Enter your citizenship: ");
scanf(" %s", &customers[n].citizenship);
printf("Please, Enter your phone number: ");
scanf(" %f", &customers[n].phone);
printf("Please, Enter your account type: ");
scanf(" %s", &customers[n].acc_type);
}
>
Each of your three functions declares its own customers array variable, so each of them has their own memory for the customer data. Moreover, the array of new_account goes out of scope at the end of the function, so you can no longer safely access the data. Because of how C compilers typically work, the customer data is not immediately erased from memory, so your view_account function might still be able to read it, but that is what is called "undefined behavior". Which means it might work, or it might not.
Try to pass down the array from the main function to the other two functions in parameters. Or, to make things simpler at first, you could also turn the local customers variable of main into a global variable.
cust customers[10];
int main(int argc, char *argv[])
{
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
...
}
void view_account(int n) {
printf("Your name is %s \n ", customers[n].name);
...
}
void new_acccount(int n)
{
customers[n].acc_no = n;
...
}
Note that there are further issues in your code, like not checking the return value of scanf or overflowing the char arrays of the struct if you enter too many characters (missing bounds and length checking), or being able to enter more than 10 customers and accessing out of bounds of the customers array, or not using customers[0] (because your customer_number starts at 1, but array indices are 0-based). But I will not go into further details here to keep the answer focused.
I try to use Y and N in a switch statement but when I try to compile it I got an error what say " error: statement requires expression of integer type ('char [0]' invalid)
switch (xx) {
"
i also got a warning " warning: incompatible pointer to integer conversion passing 'char [1]' to parameter of type 'char' [-Wint-conversion]
sucheZeichen(name, imya); "
int main() {
char name[200];
printf("Please tell me your name:");
fflush(stdin);
scanf("%s", name);
printf("%s has %i letters\n", name, langeZeichne(name));
// frage
int end = 0;
char xx[0];
char imya[1];
do {
fflush(stdin);
printf("would you like to count a letter in %s (Y / N)?\n", name);
scanf("%c", xx);
switch (xx) {
case "Y":
printf("Please enter a letter\n");
scanf("%s", imya);
sucheZeichen(name, imya);
break;
case "N":
printf("Have a nice Day!");
end = 0;
break;
default:
printf("Wrong input\n");
break;
}
}while (end==0);
}
First of all, if you want to read a letter into xx don't use an array, and definitly not an array of size 0.
Second, your switch receive an char[] instead of a char.
Next, in the cases use chars instead of strings.
Moreover, according to the information in the question, sucheZeichen gets a char as a second parameter (or an int) so the same problem with xx as an array apply for imya as well.
Also, I added \n to the scanf so it won't read the newline character.
Your code should like like:
int main() {
char name[200];
printf("Please tell me your name:");
fflush(stdin);
scanf("%s", name);
printf("%s has %i letters\n", name, langeZeichne(name));
// frage
int end = 0;
char xx;
char imya;
do {
fflush(stdin);
printf("would you like to count a letter in %s (Y / N)?\n", name);
scanf("%c\n", &xx);
switch (xx) {
case 'Y':
printf("Please enter a letter\n");
scanf("%c\n", &imya);
sucheZeichen(name, imya);
break;
case 'N':
printf("Have a nice Day!");
end = 0;
break;
default:
printf("Wrong input\n");
break;
}
}while (end==0);
}
Whenever I run this I got something like ' 196875307' as the total, could
someone tell me whats wrong with it.Here I uploaded the whole code.It says my post is mostly code and to add more details,So forgive me for typing these unnecessory things XD
#include <stdio.h>
int room;
char name[20];
int i;
void main()
{
int answr,fc[6],z=0,tot;
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("\n *********");
printf("\n MENU CARD");
printf("\n *********\n\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\t%d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER
FOOD");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
printf("Enter the main menu function here");
break;
}
case 1:do
{
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf(" %d",&fc[z]);
z++;
tot=tot+fc[z];
printf("total so far is %d",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
}while((ans=='y')||(ans=='Y'));
printf("\nEnter your room number:");
scanf(" %d",&room);
printf("\nEnter your name:");
scanf(" %s",&name);
}
}
The issue lies in your do loop. You need to initialize tot to 0, and use the user-inputted "food code" as an array index into your price array. I don't see any use for the "fc" array you've declared. This code should work for case 1 in your switch statement.
Remember that the main function returns an int in C.
do {
tot = 0;
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8) {
printf("Invalid food code\n");
return -1; // main should return int in a C program
}
tot=tot+price[z-1];
printf("total so far is %d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
} while((ans=='y')||(ans=='Y'));
I think that you should increment your counter z after you do the addition of the total with your freshly added element into the array.
1)Get the value by scanf
2)add it by using vet[z]
3)increment z.
When your code hit the sum it will try to access to a segment of memory that is filled with some other values.
What seems to be the problem in my code? I wish to make a program that makes allows the user to choose from a list of choices/menu. The user chooses one and a function runs. After the function executes the menu appears again until the user decides to quit.
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
int evaluate(int num);
int binaryPrinter(int dec);
int hexaPrinter(int dec);
int militaryTime(int hh, int mm);
int main(void)
{
int choice, x, y;
do {
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d, &choice");
(void) getchar();
switch (choice){
case 1:
printf("Enter number to be evaluated:");
scanf("%d, &x");
int evaluate(int x);
break;
case 2:
printf("Enter a decimal number: ");
scanf("%d, &x");
int binaryPrinter(int x);
break;
case 3:
printf("Enter a decimal number: ");
scanf("&d, &x");
int hexaPrinter(int x);
break;
case 4:
printf("Enter time in standard format: ");
scanf("%d:%d, &x, &y");
int militaryTime(int x, int y);
break;
default:
printf("Invalid choice. Please choose only among the choices.");
}
}while(choice != 5);
return 0;
}
This is what is displayed after inputing the number of choice: Process returned -1073741819 <0xC0000005>
-EDIT-
I have recognized the mistake I have made. But the result's still the same.
here's my new code, but same error: Process returned -1073741819 <0xC0000005>
#include <stdio.h>
#include <stdlib.h>
int evaluate(int num);
int binaryPrinter(int dec);
int hexaPrinter(int dec);
int militaryTime(int hh, int mm);
int main(void)
{
int choice, x, y;
do {
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d", &choice);
(void) getchar();
switch (choice){
case 1:
printf("Enter number to be evaluated:");
scanf("%d", &x);
evaluate(x);
break;
case 2:
printf("Enter a decimal number: ");
scanf("%d", &x);
binaryPrinter(x);
break;
case 3:
printf("Enter a decimal number: ");
scanf("%d", &x);
hexaPrinter(x);
break;
case 4:
printf("Enter time in standard format: ");
scanf("%d:%d", &x, &y);
militaryTime(x, y);
default:
printf("Invalid choice. Please choose only among the choices.");
}
}while(choice != 5);
return 0;
}
Try this code
#include <stdio.h>
#include <stdlib.h>
int evaluate(int num);
int binaryPrinter(int dec);
int hexaPrinter(int dec);
int militaryTime(int hh, int mm);
int main(void)
{
int choice, x, y;
do
{
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d", &choice);
(void) getchar();
switch (choice){
case 1:
printf("Enter number to be evaluated:");
scanf("%d", &x);
evaluate(x);
break;
case 2:
printf("Enter a decimal number: ");
scanf("%d", &x);
binaryPrinter(x);
break;
case 3:
printf("Enter a decimal number: ");
scanf("&d", &x);
hexaPrinter( x);
break;
case 4:
printf("Enter time in standard format: ");
scanf("%d:%d", &x, &y);
militaryTime( x, y);
break;
default:
printf("Invalid choice. Please choose only among the choices.");
}
}while(choice != 5);
return 0;
}
You have used wrong syntax of the scanaf()
it's not like scanf("%d,&choice");
it is like scanf("%d",&choice);
And also missed the syntax of function call
it's not like int evaluate(int x); it is like evaluate(x)
Your scanf statements are all wrong. It usually takes to parameters. A format string containing format specifiers to determine what kind of value and how many values to read and a pointer to the variable were to store the read value (multiple pointers in case of multiple specifiers).
// What you got so far
scanf("%d, &choice"); // <-- format string and pointer to variables are combined
// How it should look like
scanf("%d", &choice); // format string "%d" containing 1 format specifier to read an int
// and a pointer to the variable choice to store the read value
Ok now to the next mistake. When declaring a function you need to write down the whole function header (returnType functionName(ParameterType1 Parameter1, ParameterType2 Parameter2, ...)) however when you want to call that funtion all it needs is its name and the parameters BUT whithout theire type.
So declaring a function like this int evaluate(int num) like you did at the very beginning of your code is fine but when calling it in your switch all it needs is the name (evaluate) and the values, or variables you want to pass to the function as parameters (evaluate(x)).
So now all together:
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d", &choice); // scan an integer value and store it in choice
switch (choice)
{
case 1:
printf("Enter number to be evaluated:");
scanf("%d", &x);
evaluate(x);
break;
case 2:
...
}
I seem to have an issue with the output of my program, when i choose option 1 it works fine in terms of asking me what data I would like to add with the packets, I enter numerical figures as I am supposed to but except for the data variable output it outputs strange ASCII characters instead of the numbers I originally inputted so any help would be appreciated thank you.
#include <stdio.h>
#include <stdlib.h>
struct packet{
int source[4];
int destination[4];
int type[4];
int port[4];
char data[50];
};
void main ()
{
struct packet s[50]; //Array for structure input
int choice;
int customerCount = 0, ii = 0;
while (customerCount <= 50){
printf("What would you like to do?\n");
printf("\t1) Add a packet.\n");
printf("\t2) s all packets.\n");
printf("\t3) Save packets.\n");
printf("\t4) Clear all packets.\n");
printf("\t5) Quit the programme.\n");
scanf("%i", &choice);
switch (choice)
{
case 1: printf("\n****Adding a packet*****\n");
printf("Where is the packet from?\n");
scanf("%i", &s[customerCount].source);
printf("Where is the packet going?\n");
scanf("%i", &s[customerCount].destination);
printf("What type is the packet?\n");
scanf("%i", &s[customerCount].type);
printf("What is the packet's port?\n");
scanf("%i", &s[customerCount].port);
printf("Enter up to 50 characters of data.\n");
scanf("%s", s[customerCount].data);
customerCount++;
break;
case 2: printf("\nDisplaying Infomation\n");
for(ii = 0; ii < customerCount; ii++) {
printf("\nSource: %s", s[ii].source);
printf("\nDestination: %s", s[ii].source);
printf("\nType : %s", s[ii].type);
printf("\nPort : %s", s[ii].port);
printf("\nData: %s\n---\n", s[ii].data);
}
break;
case 3: break;
case 4: break;
case 5: break;
default: printf("\nThis is not a valid choice, please choose again\n\n");
break;
}
}
}
You're adding input to the structure's int arrays as though they're a single int and printing them as though they're strings. Make the int arrays single ints and print them with %i as the printf format specifier.
struct packet
{
int source;
int destination;
int type;
int port;
char data[50];
};
case 2:
printf("\nDisplaying Infomation\n");
for(ii = 0; ii < customerCount; ii++)
{
printf("\nSource: %i", s[ii].source);
printf("\nDestination: %i", s[ii].source);
printf("\nType : %i", s[ii].type);
printf("\nPort : %i", s[ii].port);
printf("\nData: %s\n---\n", s[ii].data);
}
break;