Function to save data as struct on C - c

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct equipamento {
int codDipositivo;
char nomeEquipamento[40];
char newVar[50];
}Equipamento;
insert(int n, int cat, Equipamento eq[])
{
int codigo;
char newVar[40];
printf("\nNew Var: ");
scanf("%s",&newVar);
eq[n].codDipositivo=newVar;
}
main()
{
Equipamento equipamento[MAX_EQ_DSP];
...a bunch of scanfs
scanf("%d",&n);
scanf("%d",&pr);
insert(n, pr, equipamento);
}
This is a sample of what I have.
on main I have a bunch of scanfs which will update the data showing on the screen but now I want to pass that data into a structure and ask for additional information.
I'm trying to use the updated code but for some reason, instead of 39 chars, it breaks down (returns to the main cycle) after the first char
printf("\nNome do Equipamento: ");
gets(nome);
strcpy(eq[n].nomeEquipamento, nome);

Your problem is this line:
eq[n].codDipositivo=newVar;
In C, you cannot assign arrays, you need to copy them element for element. Remember that C has no string data type, a string is just a NUL-terminated array of char. Luckily there is a function in the C library to help us, strcpy.
strcpy(eq[n].codDipositivo, newVar);
To get the declaration of strcpyyou need to add the following include at the top of your code:
#include <string.h>

Related

Why puts is not working in the following code?

#include <stdio.h>
#include <stdlib.h>
struct test
{
int id;
char name[20];
};
int main()
{
struct test t1;
t1.id=1;
fflush(stdin);
fgets(t1.name,20,stdin);
print((&t1.name));
print1(t1.id,&(t1.name));
}
void print(struct test *name)
{
puts(name);
}
void print1(struct test id,struct test *name)
{
printf("\n%d\n",id);
puts(name);
}
When I run this program it asks for input
test[enter]
output comes out
test
1
(then program terminates)
Why the first puts worked and why puts in second function did not? Yes, there is an option to send complete structure, but I want to know what's wrong here.
Your program does not work for several reasons:
You are calling functions that lack forward declarations - you should see warnings when your program compiles. Do not ignore them
Your functions are taking arguments of incorrect type - you should receive the type corresponding to individual fields, e.g. void print1(int id, char *name) or you should pass the whole structure, by value or by pointer, i.e. void print1(struct test t)
Once you fix these two problems, and make sure that your program compiles warning-free, with all compiler warnings enabled, the issue should be solved.
void print(struct test *name)
should be changed to
void print(char name[]) // because you wish to print a null terminated array of characters.
print((&t1.name));
should be changed to
print(t1.name); //name is the array you wish to print
You need this
void print(char *name)
{
puts(name);
}
And the call needs to be
print(t1.name);
puts takes char * (or actually const char *).
t1.name has the data type char *
Similarly
void print1(struct test id, char *name)
{
printf("\n%d\n",id);
puts(name);
}
and the call
print1(t1.id,& t1.name);
The name of an array degenerates into the address of the first element of an array . So when t1.name is passed to function, it becomes the address of the start of the char array.

How to use structs within multiple functions in C?

I want my program to ask the user to input the name of a car, the color of the car, and the type of car. I want to do this using a struct and only two functions. The first function takes in the info that the user inputs and the second function simply displays the information that was just put in. I have tried coding this but I have no idea how to use structs within two separate functions. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Automobiles {
char name_of_car[50];
char color_of_car[50];
char brand_of_car[50];
} auto;
void UserInput() {
printf("What is the name of the car?\n");
scanf(" %s", auto.name_of_car);
printf("What is the color of the car?\n");
scanf(" %s", auto.color_of_car);
printf("What is the brand of the car?\n");
scanf(" %s", auto.brand_of_car);
}
void DisplayOutput() {
printf("%s", auto.name_of_car);
printf("%s", auto.color_of_car);
printf("%s", auto.brand_of_car);
}
int main() {
UserInput();
DisplayOutput();
return 0;
}
If you want to pass a structure to your functions as parameters, here is a possible example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Automobile {
char name_of_car[50];
char color_of_car[50];
char brand_of_car[50];
};
void UserInput(struct Automobile *auto) {
printf("What is the name of the car?\n");
scanf(" %s", auto->name_of_car);
printf("What is the color of the car?\n");
scanf(" %s", auto->color_of_car);
printf("What is the brand of the car?\n");
scanf(" %s", auto->brand_of_car);
}
void DisplayOutput(struct Automobile *auto) {
printf("%s", auto->name_of_car);
printf("%s", auto->color_of_car);
printf("%s", auto->brand_of_car);
}
int main() {
// Declare an instance of an Automobile structure.
struct Automobile auto;
// Declare and initialize a pointer to an Automobile structure.
struct Automobile *p_auto = &auto;
// Pass the pointer to the functions.
UserInput(p_auto);
DisplayOutput(p_auto);
return 0;
}
In this example, an instance of the Automobile structure is allocated as a local to the main() function. Then we declare a pointer, and initialize it so that it points to that local instance. Then we pass that pointer to the functions.
Your original code declared an instance of the Automobile structure as a global value and accessed it from within your functions. A possible implementation, but not always an appropriate one...
If you want to learn more, read up on "Pass by value" and "Pass by reference" topics at your local C knowledge provider.

Assigning a character array to a character array in a structure

I am working on a project that requires that I make an array of a certain structure type. The structure looks like this:
typedef struct
{
char array[30];
int num;
}structure
I have declared an array of these structures like this:
structure struct1[5];
I passed this structure array to a function which fills the first four elements with a string and a number. The fifth is left blank. Later in the program, I pass the array again and try to set the string in the structure to a user determined string using gets(). I am getting this error:
438:19: error: incompatible types when assigning to type 'char[30]' from type 'char *'
If I need to provide more clarification, please tell me.
Thanks!
EDIT: Here is what I am doing:
typedef struct
{
char array[30];
int num;
}structure;
void fillStructs(structure[]);
void userEditStructs(structure[]);
main()
{
structure myStructs[5];
fillStructs(myStructs);
userEditStructs(myStructs);
return 0;
}
void fillStructs(structure s[])
{
//code to fill myStructs elements 0-3.
}
void userEditStructs(structure s[])
{
char newArr[30];
int newNum;
printf("Please enter your string:\n\nEntry:\t");
gets(newArr);
printf("Please enter your number:\n\nEntry:\t");
scanf("%i", newNum);
s[5].array = newArr;
s[5].num = newNum;
}
you are doing something like this
char a[20];
a = "bla";
you cant do this.
do strcpy(a,"bla"); instead. ( #include <string.h> )
Without looking at the code you are probably trying to do something like:
struct[4].array = gets(<unknown>);
which won't work, as you can't assign the returned char* from gets to an array as the compiler says. You are also using gets, which is strongly discouraged as it performs no bounds checking. Instead, do the following:
fgets(struct[4].array, sizeof(struct[4].array), stdin);
which will do proper bounds checking.

Allocating memory for array in struct (in C)

I need to define a type-struct in C that contains an array to be malloc'd as:
#include <stdio.h>
#include <stdlib.h>
typedef struct mine
{
int N;
double *A;
} mine;
int main(int argc, char** argv)
{
int i;
mine *m=malloc(sizeof(mine));
printf("sizeof(mine)=%d\n",sizeof(mine));
scanf("Enter array size: %d",&(m->N));
m->A=malloc((m->N)*sizeof(double));
for(i=0; i < m->N; i++)
m->A[i]=i+0.23;
printf("First array element: %lf",m->A[0]);
return (EXIT_SUCCESS);
}
The program compiles and runs, and the integer assignment seems to work fine. The array is not working as it should, however.
Any suggestions? I would like m to remain a pointer (to pass to functions etc.).
Thanks.
This is your problem:
scanf("Enter array size: %d",&(m->N));
It should be two separate steps:
printf("Enter array size: ");
scanf("%d",&(m->N));
(and for debugging checking:)
printf("The size entered appears to be %d\n", m->N);
That way, you know if you got the value you intended to get!
If #abelenky answered your question fine, but I was always told to cast the results of malloc from the void * it returns into whatever you are actually working with.
mine *m = (mine *)malloc(sizeof(mine));

Programming with functions and structures using C, getting strange output, no errors

I'm learning a bit C and i'm doing an exercise where i use structures and functions to collect employee infos and just print them out.
I'm declaring the functions and the struct in the header since i need them in both of the other files.
//employee.h
int addEmployee(void);
int printEmployee(int i);
struct employeelist
{
char last [20];
char first[20];
int pnumber;
int salary;
};
The "core" file is executing the both functions. The first function asks for the number of employees and gives a value back for the second function where the information is collected and stored. There are no errors and i've checked the code several times.
//employee.c
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int numE;
int i;
int addEmployee(void)
{
struct employeelist employee[5];
int numE;
printf("How many employees do you want to add to the list?: ");
scanf("%d", &numE);
printf("Please type in the last name, the first name,\nthe personal number and the salary of your employees.\n");
for (i=0; i < numE; i++)
{
printf("Last name: ");
scanf("%s", employee[i].last);
printf("First name: ");
scanf("%s", employee[i].first);
printf("Personal number: ");
scanf("%d", &employee[i].pnumber);
printf("Salary: ");
scanf("%d", &employee[i].salary);
}
return numE;
}
int printEmployee(int emp)
{
struct employeelist employee[5];
for (i=0; i < emp; i++)
{
printf("Last name: {%s}\nFirst name: {%s}\nPersonal number: {%d}\nSalary: {%d}\n",employee[i].last,employee[i].first, employee[i].pnumber, employee[i].salary);
}
getchar();
getchar();
return emp;
}
The last file contains the main() function to execute the functions above.
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int emp;
int main ()
{
struct employeelist employee[5];
int emp = addEmployee();
printEmployee(emp);
return 0;
}
Now my problem is that everything works only the output is incorrect. I can't even say what it is. Some kind of random mix of signs, letters and numbers. Since i have no idea where my mistake is, i would be glad about any advise to solve this problem. Thank you.
I have added a screenshot of my output. Maybe it helps.
You're trying to use a local variable, which ceases to exist when the function returns.
int addEmployee(void)
{
struct employeelist employee[5];
/* ... */
}
The variable employee only exists inside the addEmployee() function; and it is a different object every time the function is called.
int printEmployee(int emp)
{
struct employeelist employee[5];
/* ... */
}
This employee has no relation to the one in addEmployee.
But don't do the easy thing now (*); do the right thing: declare the array in the main() function and pass it around.
//employee.h
struct employeelist
{
char last [20];
char first[20];
int pnumber;
int salary;
};
/* add up to `maxemp` employees to the array and
** return number of employees added */
int addEmployee(struct employeelist *, int maxemp);
/* print all employees from index 0 to (nemp - 1) */
int printEmployee(struct employeelist *, int nemp);
Declare an array in main(), and pass it around
#include "employee.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main ()
{
int emp;
struct employeelist employee[5];
int emp = addEmployee(employee, 5);
printEmployee(employee, emp);
return 0;
}
(*) Don't declare a global variable for employees
Edited employee.h and added a main() function
You have a brand new variable in your print function that isn't even initialized. So it contains only garbage and that is printed
The heart of the problem is that you're working with three different arrays of employees instead of the one array that you think you've got. Anything declared within a pair of curly braces in C only 'exists' while the program is executing code inside those braces. You've declared three different arrays of employee structs in three different blocks of code.
To point you in the right direction (irrespective of whether this is homework or self-study, this is a learning exercise so just fixing your code probably isn't what you want) you should think about how you can pass the same employee array to each of your functions in turn. (EDIT: pmg beat me to it.)
Declare the array once, in your main() function as you've already done, and modify your two functions printEmployee() and addEmployee() to take that array as a parameter instead of declaring their own local arrays.
Here is a very simple example using ints showing how parameters and return values work. You'll have to do some reading about pointers to extend this to your case.
int main() {
int number = 2;
int newNumber;
newNumber = timesTwo(number);
printf("number: %d newNumber: %d", number, newNumber);
}
int timesTwo(int param) {
return param * 2;
}
Before you start breaking things out into separate files and working with structs and pointers it is a good idea to practice the concepts of functions, parameters and variables by building simple programs in a single file.
You declare the employee array locally to both functions, so they cannot access each other's data.
The main issue, as others have already said, is that you are declaring a struct employeelist employee[5] in each of your functions. This makes those variables local to their functions and thus inaccessable from one function to the other. So, when printEmployee goes to print, the data it is printing is gibberish.
There are a few things needed to fix this:
Make one declaration of your employee list in your main (which you already have) and then pass that into the functions. You'll need to do the passing by means of the array name so that the functions will treat the array properly.
As a result of the above, you'll need to move the struct declaration to be above the function prototypes and then change the prototypes in employee.h to accomodate the passing of the employeelist.
You'll have to check that the user doesn't try to enter more records than your array has space for. Alternatively, you could just declare a pointer in the main and malloc() the needed memory in the addEmployee function.
A few other suggestions to make things a little easier on yourself:
Call your struct employee (or something like that) and your array employeelist (or something similar).
Use typedef on your struct to shorten & simplify your declarations.
Change your printEmployee to be a void function (i.e. void return type).
Take a look.. Well distribued and simple to read, it just needs a little improvement to become bigger and do the work u want.
typedef struct
{
char last [20];
char first[20];
long int pnumber;
int salary;
}employee;
/* the two functions clearly declared */
int addEmployee(employee const wEmployeeList[]);
void printEmployee( employee const wEmployeeList[], int );
int main()
{
int numberE;
employee employeeList[2];
numberE = addEmployee(employeeList);
printEmployee(employeeList, numberE);
return 0;
}
int addEmployee(employee const wEmployeeList[2]){
int i;
for (i=0; i < 2; i++)
{
printf("Last name: ");
scanf("%s", wEmployeeList[i].last);
printf("First name: ");
scanf("%s", wEmployeeList[i].first);
printf("Personal number: ");
scanf("%ld", &wEmployeeList[i].pnumber);
printf("Salary: ");
scanf("%d", &wEmployeeList[i].salary);
}
return 2;
}
void printEmployee(employee const wEmployeeList[2], int numberEmployee){
int i;
for (i=0; i < numberEmployee; i++)
{
printf("\n\nLast name: %s\nFirst name: %s\nPersonal number: {%ld}\nSalary: {%d}\n \n",wEmployeeList[i].last,wEmployeeList[i].first, wEmployeeList[i].pnumber, wEmployeeList[i].salary);
}
}

Resources