I have an assignment for C beginner class: I'm supposed to create a structure that has one variable (named value) and one pointer to the list. I'm supposed to prompt the user for 5 values as input and store them in the linked list. Then print out the list. I can't figure out how to store input into the list. I did manage to write a program in which I initialize the 5 values. But I don't know how to accept input and store it into the list.
Here's the working program where I initialize the values:
#include <stdio.h>
struct list
{
double value;
struct list *nextVal;
};
int main()
{
struct list v1 = {10};
struct list v2 = {17.97};
struct list v3 = {166};
struct list v4 = {2};
struct list v5 = {387.55};
struct list *first;
first = &v1;
v1.nextVal = &v2;
v2.nextVal = &v3;
v3.nextVal = &v4;
v4.nextVal = &v5;
v5.nextVal = NULL;
printf("All the values are: %.2f, %.2f, %.2f, %.2f, %.2f.",
first->value,v1.nextVal->value,v2.nextVal->value,
v3.nextVal->value,v4.nextVal->value);
return 0;
}
Here's a program where I tried getting user input and storing that into the list. (I only have 2 values instead of 5, cuz it's easier to work with that when trying to make it work.) When I compile this program, I get no errors. When I run it, I am properly prompted for the two input values; however, when the output that the program prints just writes 0 for both values. My assumption is that I'm storing the value into the list wrong - because I don't know how it's actually done. (Can't find any info in my textbook or online.) Last night someone commented on a different question I had to try using breakpoint to find out exactly where the problem is - I've been trying to figure it out since then but don't know how to do that yet. (I'm assuming it's something very simple - but everywhere I looked online, people explain it in a way that seems like I'm supposed to know what they're talking about - which I don't - And honestly, even if I could figure it out, I still wouldn't know what to do with that information, since I just can't find any information on how to store user input into a linked list.) Anyways, so here's my trial program that complies and runs but gives me 0 for both final values:
#include <stdio.h>
struct list
{
double value;
struct list *nextVal;
};
int main()
{
double val1,val2;
printf("Please enter a number: ");
scanf("%f",&val1);
printf("Please enter a number: ");
scanf("%f",&val2);
struct list v1 = {val1};
struct list v2 = {val2};
struct list *first;
first = &v1;
v1.nextVal = &v2;
v2.nextVal = NULL;
printf("The two values entered are %.2f and %.2f.",
first->value,v1.nextVal->value);
return 0;
}
Thank you in advance! And I'm reaaaally a beginner - so even if you suggest something super easy - I might have no clue what it is..so please explain! Thank you!
scanf("%f",&val1);
%f requires a float variable but the given variable is a double. Use %lf for double.
scanf("%lf",&val1);
Your compiler should have given you a warning for that and you should always heed those and resolve them:
warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=]
scanf("%f",&val1);
A few extra words of advice though they are not directly addressing your question:
Always check the function return values. Specifically, check scanf to ensure that the expected input was parsed. The code as it is will fail if the user enters something unexpected.
Break up your code into functions. Specifically, make a seperate insert function to add items to the linked list.
Use loops where you need to repeat code. Such as for the scanf calls. That way it can be easily extended when you want to take more input.
Try compiling with warnings on etc. At a minimum I use this...
gcc -Wall -pedantic -std=c11
Working version
include <stdio.h>
struct list
{
double value;
struct list *nextVal;
};
int main()
{
double val1,val2;
printf("Please enter a number: ");
scanf("%lf",&val1);
printf("Please enter a number: ");
scanf("%lf",&val2);
struct list v1 = {val1};
struct list v2 = {val2};
struct list *first;
first = &v1;
v1.nextVal = &v2;
v2.nextVal = NULL;
printf("The two values entered are %.2f and %.2f.",
first->value,v1.nextVal->value);
return 0;
}
You were scanning quotes and trying to assign it to a double. A good compiler would give you a warning..
scanf.c:14:14: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f",&val1);
~~ ^~~~~
%lf
scanf.c:16:14: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f",&val2);
~~ ^~~~~
%lf
Related
I have a problem with a small project, I have to create a structure containing a person's data,I have to do data entry via a function using pointers.
I don't understand why when I try to enter the weight the program ends with this error:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
I made an example of the code that is giving me problems:
typedef struct{
char name[DIM];
char surname[DIM];
int height;
float weight;
}Record;
int main() {
Record subj;
insRecord(&subj);
}
void insRecord(Record *subj){
printf("\nName ");
scanf("%64[^\n]s", subj->name);
cleanBuffer();
printf("\nSurname ");
scanf("%64[^\n]s", subj->surname);
cleanBuffer();
printf("\nEight ");
scanf("%3s", subj->height);
cleanBuffer();
printf("\nWeight ");
scanf("%6s", subj->weight);
cleanBuffer();
}
int cleanBuffer(){
int cont= 0;
char c;
do{
cont++;
c = getchar();
}while(c != '\n');
return cont;
}
(I only wrote the main functions).
Furthermore, compiler is giving warnings on height and weight scanf() statements:
Format specifies type 'char *' but the argument has type 'int' (for height)
Format specifies type 'char *' but the argument has type 'double' (for weight)
Could you tell me how can I solve?
PS the project is divided into several files (3 files).
In main.c I wrote the insRecord() function, in struct.h I wrote the Record structure, in struct.c I wrote cleanBuffer() function.
You are reading a string (%s) and try to store that in a float. If you use the flag %f for weight and %d for height it will probably work better. Remember that you should provide a pointer to the float and int that you want to store the data in, you are not doing that in your example.
Have a look at the scanf documentation:
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
Good luck
I am getting a compiler error on my program . I use Dev-C++ with -c99 -wall and -pedantic .
#include <stdio.h>
#include <stdlib.h>
int main(){
int size,dial,isListEmpty=0,init,i,variableSize,totalSize=0;//Some values I am using
printf("Welcome to your New Phone ! Please select the size of contact list\n");//Welcome Message
scanf("%d", &size);//input of size
int *listFirstName = (int*)malloc(size*sizeof(int));//Last name (in numbers)
int *listLastName = (int*)malloc(size*sizeof(int));// First name in numbers
int *listNumber = (int*)malloc(sizeof(int));// the phone number
for (init=0 ; init< size ; init++){//initialization of arrays
listFirstName[init]=-1;
listLastName[init]=-1;
listNumber[init]=-1;
}
This is where the compiler shows that there is an error.
if (dial==3){
int linearAnswer,possibleLN=0, possibleFN=0,flag=0,j=0;
printf("Would you like to search by Last Name , First Name? Please press 1 or 2\n");
scanf("%d",&linearAnswer);
if(linearAnswer==1){
scanf("%d",&possibleLN);
while(j<size){
if(listLastName[j]==possibleLN){
variableSize=j+1;
printf("%d",variableSize);
printf("\nLast Name:%d\t",&listLastName);
printf("First Name:%d\t",&listFirstName);
printf("Phone Number:%d",&listNumber);
flag=1;
}
j++;
}
The compiler error :
[Warning] format '%d' expects argument of type 'int', but argument 2 has type 'int **' [-Wformat=]
What does the program do : It copies some basic functions of a phone from 1990s . First , the user selects the size of the contact list . Then he gets to add a contact, find a contact or list all contacts or exit.
Edit : Removed the pictures and added more detail
listNumber is declared as a pointer to an int: int*.
&listNumer is of type int**.
printf needs an int as parameter for a %d.
What you probably wanted to do is:
printf("%d", *listLastName);
The * dereferences listLastName, i.e. lets you access the int value.
I'm having problems with a function that I use to write to an element of an array.
I think it might be because I'm not passing the array of struct correctly. I was wondering if someone can point out how to do this correctly. I've been screwing it up more than fixing it.
let's say I have a function menu.c
I declare my struct newPerson person[MAX_PERSONS];
I then run my function addPerson(person, &num);
which is the following
void addPerson(newPerson *pers, int *num){
pers[*num] = (newPerson) {
"Michelle", "Leo", "6136458798", STUDENT,
.data = {.s = {9, 1234.50, 3}}
};
*num = *num + 1;
}
It runs, but won't print out correctly, I'm guessing because it doesn't write where I want it to pers[num]. I tried calling the function this way also addPerson(&person, &num); instead of just addPerson(person, &num); but then I receive this error
warning: passing argument 1 of ‘addPerson’ from incompatible pointer type [enabled by default]
and
note: expected ‘struct newPerson ’ but argument is of type ‘struct newPerson ()[20]’
I've tried changing the function to void addPerson(newPerson *pers[], int *num){ as well but nothing there. Was wondering if anyone can point out what I'm doing wrong here and how I can fix my problem. Any help would be appreciated, thanks!
Forgot to mention that the addPerson function works in some places where I run it.
int menu(int num) {
newPerson person[MAX_PERSONS];
//printf("THE NUMBER START OF MENU IS %d\n", num); test counter
//addPerson(person, &num); <- WRITES AND READS PROPERLY IF DONE HERE
int option;
printf(
"\n\tPlease choose one of the following options to continue (0-9): ");
scanf("%d", &option);
if (option == 1) { //program will ask for name input
addPerson(person, &num); <- HOWEVER IT DOES NOT WRITE OR READ PROPERLY HERE
menu(num);
}
Both functions are called in menu.c
However when I call addPerson in the if statement, it does not write/read properly.
Just solved the problem by declaring the struct as static!
static newPerson person[MAX_PERSONS];
I'm not sure if this is taboo or anything, but it fixed my problem!
By making static you have made the code inefficient as the memory for
the data structure has been set aside regardless of whether it is
needed or not while the program is executing.(With a static data
structure, the size of the structure is fixed.)
Declare the function like
void addPerson(newPerson *pers[],int *num)
call the function like
void addPerson(newPerson *pers, int *num);
OR
void addPerson(newPerson pers[], int *num);
I was able to get it working by declaring the struct as static
static newPerson person[MAX_PERSONS];
Not sure if this is an actual fix or if it's just masking my problem though.
I am a newbie to C Programming and I am learning to pass a struct as a parameter to a function (as part of my course) by value. I am using gcc ver 4.6.3 on Ubuntu Linux 12.04LTS
The following is the source code which seems logically and syntactically correct (to me) but I get errors when compiling it:
#include<stdio.h>
struct sal {
char name[30];
int no_of_days_worked;
int daily_wage;
};
typedef struct sal Sal;
void main()
{
Sal salary;
int amount_payable;
salary=get_data(salary); //Passing struct as function arguments
printf("\nThe name of the Employee is %s",salary.name);
printf("\nNumber of days worked is %d",salary.no_of_days_worked);
printf("\nThe daily wage of the employees is %d",salary.daily_wage);
amount_payable=wages(salary);
printf("\nThe amount payable to %s is %d",salary.name,amount_payable);
}
Sal get_data(Sal income)
{
printf("\nEnter the name of the Employee: \n");
scanf("%s",&income.name);
printf("\nEnter the number of days worked:\n");
scanf("%d",&income.no_of_days_worked);
printf("\nEnter the employee daily wages:\n");
scanf("%d",&income.daily_wage);
return(income); //Return back a struct data type
}
int wages(Sal x)
{
int total_salary;
total_salary=x.no_of_days_worked*x.daily_wage;
return(total_salary);
}
On compiling the code I get the following errors:
struct_to_function.c: In function ‘main’:
struct_to_function.c:15:7: error: incompatible types when assigning to type ‘Sal’ from type ‘int’
struct_to_function.c: At top level:
struct_to_function.c:22:5: error: conflicting types for ‘get_data’
struct_to_function.c:15:8: note: previous implicit declaration of ‘get_data’ was here
struct_to_function.c: In function ‘get_data’:
struct_to_function.c:25:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[30]’ [-Wformat]
I think it has some thing to do with the implementation or execution plan of the gcc compiler whether the compiler is using a stack or registers. Again these are just my amateurish assumptions.
When the C compiler encounters the call to get_data from main, it has no idea what the return type is (since it has seen neither a function declaration nor a function definition), so it assumes int. This gives you the first warning, because salary is incompatible with int in the assignment. The compiler keeps going, now thinking that get_data returns int, and then it complains when it encounters the actual definition of get_data.
You should either add a function prototype before main, or make sure that functions are always defined before being called (by rearranging their order in the source code).
The final warning is because the scanf with a %s specifier is expecting a char*, but you gave it something of type char (*)[30]. Leave off the & when passing an array.
Just add the following before main:
Sal get_data(Sal income);
int wages(Sal x);
You have to pass a pointer to the structure. When you try to pass the structure itself, the C compiler tries to make a copy of it, but it doesn't know how to do that (you would need to use C++ to be able to define that) so it's an error.
You didn't declare the functions before you used them, so the compiler created it's own default definition for you. You have to declare a function before you reference it.
Also, it's bad practice to pass the structure by value and then modify it and pass it back. Better to just pass the pointer to the object you want to modify.
So:
int wages( Sal x );
void get_data( Sal* income );
void main()
{
Sal salary;
int amount_payable;
get_data( &salary ); //Passing struct as function arguments
// print stuff
amount_payable = wages( salary );
// print stuff
}
void get_data( Sal* income )
{
printf( "\nEnter the name of the Employee: \n" );
scanf( "%s", income->name );
printf( "\nEnter the number of days worked:\n" );
scanf( "%d", &(income->no_of_days_worked) );
printf( "\nEnter the employee daily wages:\n" );
scanf( "%d", &(income->daily_wage) );
}
int wages( Sal x )
{
int total_salary;
total_salary = x.no_of_days_worked * x.daily_wage;
return total_salary;
}
I have gone under a problem while coding in c (i am not experienced programmer).
I have a structure like this
struct afreq
{
int freq;
unsigned char sym;
short int left,right,next;
};
in main function :
struct afreq data[50] ;
int size = manipulation(data, count); //this function do some manipulation and
returns size of int type.And i use this size in the function call below:
dictionary(data,var,size);
The problem creating part is here:
///////////////////////////// Definition of Dictionary function /////////////////////////////////////////
dictionary(struct afreq data[] ,char *var,size_t dataSize)// function definition create problem in first argument when caled from the another recursive function call inside this function.
dictionary(struct afreq data[] ,char *var,size_t dataSize)
{
int i;
printf("\n data: %d\n", dataSize);
for(i=2;i<dataSize;++i)
{
if(data[i].left=='\0')
{ int correspondance[data[30];
char temp[30];
strcpy(temp, var);
strcat(temp, "0");
printf("check1");
dictionary(data[correspondance[data[i].left]], temp,dataSize); //error here
}
printf("\n");
}
}
What i want to do using this?
I have to read the alphabets from a file given as sole argument. The file is "Input.txt" and contains inside 'abcdef' (i calculate their frequency in my program) and then i save them in an array in the format [symbol Frequency LeftChild RightChild] (example: [a 1 0 0] [b 2 0 0 ] [c 3 a b] etc.(it's like huffman code)).
Up to here i have done everything properly. But when i try to print the dictionary like (as we have in huffman (path in o and 1)) (In the example we can see that "c" is parent and path of "a" is "o" and "b" is "1"). To implement this part i have written the code above, which creates error in first argument of function call.
Here is the complete code (But please do not forget to include "Input.txt" file at sole argument which contains "abcdef" .
Here is the output:
hp#ubuntu:~/Desktop/Internship_Xav/Task2$ gcc ttask.c -o ttask
improve.c: In function ‘dictionary’:
improve.c:85:2: error: incompatible type for argument 1 of ‘dictionary’
improve.c:74:1: note: expected ‘struct afreq *’ but argument is of type ‘struct afreq’
The error is, essentially, what your compiler says it is. You are passing, as first argument, data[i].left, which is of type short int, whereas a pointer to struct afreq is needed. The only reason why it compiles anyway is because gcc, by default, allows conversions between int and pointer (but there's not many reasons why you would want to do that).
If I understand correctly what you are trying to do - you want to call recursively your "dictionary" function on what seems to be a tree. The problem is that that structure is not really well defined. You are trying to "index" the nodes of the tree with their value (that's what I understand with the data[i].left), but there is no way to "make the link" between, say, 'a', and "the struct afreq that has 'a' as a symbol. You either need to make a correspondance table somewhere and make a call to it, or you need to transform left and right in your structure into pointers to the corresponding structure.
Good luck!