Sending values to another function using structures - Whats wrong with that? - c

I have two functions and a structure. My first function getChange does calculations and stores them in two arrays. My second function printChange should accept these values of two arrays and just print arrays using a simple for loop.
I am trying to use my structure Change to send these arrays across to the print function, but I can't seem to do it.
I thought of creating two arrays in my structure and then simply setting array in function = to array in struct and then do the opposite in print func. But I can't!
# include <stdio.h>
#include<stdlib.h>
struct cashback{
int value[8];
int money[8];
};
typedef struct cashback Change;
int getChange(int paid, int cost){
int r, k, cntr, c=1, value[8], money[8]={200,100,50,20,10,5,2,1};
Change store;
if (cost>paid){
printf("\t Insufficient Funds! \n");
getchar();
exit(1);
}
r=paid-cost;
value[0]=r/money[0];
k=r%money[0];
for(money[c], cntr=1;cntr<8;c++, cntr++){
if (k !=0){
value[c]= k/money[c];
k=k%money[c];
}
else{
value[c]=0;
k=k/money[c];
}
}
store.value[8]=value[8];
store.money[8]=money[8]; //Sending calculation to Struct(store)
}
void printChange() {
Change store;
int i, j;
for (i=0; i<8; i++) {
printf("%i \t",store.money[i] );
}
printf("\n \n");
for (j=0; j<8; j++) {
printf("%i \t ", store.value[j] );
}
}
int main(){
Change store;
getChange(90,50);
printChange();
getchar();
}

When you write:
Change store;
inside a function, that means there is a variable called store inside that function only. In your code you have three separate variables (all called store).
Instead you need to pass the variable around where it is needed.
You currently have getChange returning int but you never actually return a value. Instead you should make this return the change:
Change getChange(int paid, int cost)
{
Change change;
// ...
return change;
}
Similarly, the printChange function should be:
void printChange(Change change)
{
// ...
}
and your main function will look like:
Change store;
store = getChange(90, 50);
printChange(store);

OK, first of all inside the 'getChange', you don't use the 'Change' struct at all. Apart from using it in this declaration: Change a;
Also, there is certainly an error here: a.value =. With what is equal?
So, the money and value arrays that you declare inside 'getChange' have nothing to do with your struct.
And finally, it doesn't seem that printChange has anything to do with the rest of the program.

You can pass to both functions pointer to Change structure. The structure can be defined inside main:
int getChange(int paid, int cost, Change* a){
//...
a->value[c] = ...
//...
}
void printChange(Change* a) {
//...
printf("%i \t", a->value[i]);
//...
}
int main(){
Change a;
getChange(90,50, &a);
getchar(&a);
}

Related

How can i use only one function showCnt() to show the members of struct arrays? How to pass parameters?

I'm learning a piece of code, I don't know how to implement this function using only one function? How to pass parameters to the function?
#include <stdio.h>
struct colleagues {
int female[10];
int male[10];
} teams[20];
void func(int count[])
{
for (int i = 0; i < 10; i++) {
printf("%d\n", count[i]);
}
}
//FIXME
void showCnt(void (*function)(int *), int XXX[])
{
for (int n = 0; n < 20; n++) {
func(teams[n].XXX);
}
}
int main()
{
//How can i just use only one function showCnt to do this work???, I'm so appreciated.
//***FIXME, How can i pass parameters "teams.female" to showCnt???***
showCnt(function, teams.female);
showCnt(function, teams.male);
return 0;
}
Sorry, I didn't say it clearly. I don't know how to pass the parameters "teams.male" as a array to showCnt(), I'm wondering how to call showCnt() twice separately to print the info.
For example, first, It calls showCnt(teamXX.female), second, it calls showCnt(teamXXX.male). I don't know if I can pass parameters to showCnt() to make "func(team[n].male)" and "func(team[n].female)" working properly.
If I understand you correctly, you want to only call showCnt as
showCnt(function);
and it should print both teams.female and teams.male?
Then to begin with remove the (erroneous) count argument from the function showCnt. Then inside the loop of showCnt call function twice with teams[n].female and teams[n].male.

How do I use the value of a variable in a function else where?

I have a certain program that lets you register members and save their name and birthdate into arrays. The particular function that does this registration uses the following code;
char regmember (struct member a[])
{
int i = 0;
char wow;
do
{
//registration
printf("\n Do you want to add someone else (y/n):");
scanf(" %c",&wow);
i++
}while(wow != 'n');
int nrofmembers = i;
return nrofmembers;
}
-> I save the user input by using
scanf("%s",a[i].name) and scanf("%d",&a[i].ID);
which is why I am using i++. As you realize, the int variable i, will hold the number of members who have been registered. I want to utilize this info in order to use it in loops in other functions, so I went on to save the value of i in another int variable...
int nrofmembers = i;
My problem is, I can't use that variable (nrofmembers) else where, even though I tried returning it, any advice?
you need both to get i in parameter and to return the new value, you can do
int regmember (struct member a[], int i)
{
... use and modify i
return i;
}
or using it as an input-output variable
void regmember (struct member a[], int * i)
{
... use and modify *i
}
In the first case the caller do for instance :
int i = 0;
for (...) {
...
i = regmember(..., i);
...
}
and in the second case :
int i = 0;
for (...) {
...
regmember(..., &i);
...
}
Suppose you keep the members in a global array, then you can manage how many members are in your array also as a global variable, for example
struct member gMembers[MAX_MEMBERS];
int gnMembers;
Your function can now operate on this array directly:
int regmember (void)
{
if (gnMembers < MAX_MEMBERS)
{
// add member
if (scanf("%s",gMembers[gnMembers].name)==1
&& scanf("%d",&gMembers[gnMembers].ID)==1) {
gnMembers++;
return 1; // success
}
}
return 0; // array full or scanf error
}

Storing Data in Stucts Containing Arrays in a Header File

I am currently trying to store information that is input from a function to a struct declared in my header file and utilize it within the main file. I cannot use struct arrays because I am not allowed to allocate memory.
header file
#ifndef HOMEWORK_H_
#define HOMEWORK_H_
typedef struct
{
int CourseID[25];
char CourseName[100][25];
}Course;
void NewCourse(void);
#endif
My code
#include <stdio.h>
#include <stdlib.h>
#include "Homework.h"
void NewCourse()
{
int i;
int CNumber = 0;
Course storeC;
for(i = 0; i < 0; i++)
{
if(storeC.CourseID[i] == 0)
{
if(storeC.CourseName[i] == NULL)
{
int CNumber = i;
break;
}
}
}
printf("%d\n", CNumber);
printf("Please enter the course's ID number: ");
scanf("%d", &storeC.CourseID[CNumber]);
printf("Please enter the course's name: ");
scanf("%s", storeC.CourseName[CNumber]);
}
and my main does not really apply since the problem lies within storing the data.
A few things to keep in mind is I must utilize a separate file for my functions and I must use a header file for my structs.
I know my for loop to determine where in the array may not be effective, but I am not so worried about it as of right now.
My question is how do I store the data from this function to the
header file?
Update
I changed the main function to fit everything else and I end up with this error now.
a label can only be part of a statement and a declaration is not a
statement
The code in main is:
switch(Option)
{
case 1:
Course c = NewCourse();
printf("%d\n%s\n", c.CourseID[0], c.CourseName[0]); // For testing purposes
break;
What is causing the error because it says it stems from line 29 which is the Course c = NewCourse();?
Change NewCourse to return a Course.
Course NewCourse(void);
Change the implementation to:
Course NewCourse()
{
int i;
int CNumber = 0;
Course storeC;
...
return storeC;
}
Change main accordingly.
int main()
{
Course c = NewCourse();
}
PS
You said,
I cannot use struct arrays because I am not allowed to allocate memory.
I assume that to mean that you cannot use dynamic memory allocation. If you are allowed to create an array of structs in the stack, you can simplify your code by using:
typedef struct
{
int CourseID[25];
char CourseName[100];
}Course;
void NewCourse(Course course[]);
and in main, use:
Course courses[25];
NewCourse(courses)
In response to your update
You needed to add a scope block { } around the code as follows:
int main()
{
{
Course c = NewCourse();
}
}
This should resolve your error and allow your code to compile.
Additionally, you have an error in manipulating the CNumber Variable. It is declared twice, with different scopes:
int CNumber = 0; // the first definition with the scope of the NewCourse Function
Then inside the test, with a block scope:
if(storeC.CourseID[i] == 0)
{
if(storeC.CourseName[i] == NULL)
{
int CNumber = i; // block-scope. This is not the same CNumber Variable (todo: Omit int)
break;
}
}
As a result, when you reference it later in
printf("%d\n", CNumber);
printf("Please enter the course's ID number: ");
scanf("%d", &storeC.CourseID[CNumber]);
printf("Please enter the course's name: ");
scanf("%s", storeC.CourseName[CNumber]);
It will be always reference the function scope variable, which is always be zero.
Solution: omit the int declaration inside the test:
if(storeC.CourseName[i] == NULL)
{
CNumber = i;
break;
}

How to use values from functions in C

I'm trying to work on a project where I'm forbidden from using global variables. In my project, I have the following function:
int addAccount()
{
int ID_number = 0;
int ID;
int ID_array[10];
double account_balance;
double balance_array[10];
int choice = getChoice ();
if (choice == 1)
{
if (ID_number + 1 > 10)
{
printf("Error\n");
}
else
{
ID_number = ID_number + 1;
printf("Please enter the id\n");
scanf("%d", &ID);
ID_array[ID_number - 1] = ID;
printf("Please enter the starting balance\n");
scanf("%lf", &account_balance);
balance_array[ID_number - 1] = account_balance;
}
}
return;
I need to somehow get the values for several of these variables and use them in another function (particularly ID, ID_number, and account_balance). The function that I need these values for is as follows:
void displayAccounts ()
{
int count;
int choice = getChoice ();
int ID_number = ID_number ();
if (choice == 2)
{
for (count = 0; count < ID_number; count++)
{
printf("Account #%d: ID is %d\n", count + 1, ID_array[count]);
printf("Account balance is %.2lf\n", balance_array[count]);
}
}
}
I know how to return one value, but I don't know how to make multiple values usable outside of the function where they occur. Is what I'm trying to do even possible or is it likely that I'm going about my project the wrong way?
Use a struct:
struct Account
{
int count;
int ID_number;
int balance_array[10];
// etc etc
};
Pass a pointer to addAccount:
void addAccount(struct Account *account)
{
account->ID_number = 0;
// etc
}
And then pass it to displayAccounts
void displayAccount(struct Account *account)
{
}
Eg:
struct Account account;
addAccount(&account);
displayAccount(&account);
Note that in C you need to use the struct prefix unless you typedef the struct.
The most obvious choice is to create a struct, which can have any number of fields (including arrays), and which can be both passed to and returned from a function. In that way you can pass around the necessary state.
You can of course also optimize it a bit by having a root function define the struct variable, and then just pass around pointers to the same instance.
You can use a structure to send the values.
Also the pointers can be a good alternate to return multiple values in C.
You can Refer to The following links too:
http://www.stackoverflow.com/questions/2620146/how-do-i-return-multiple-values-from-a-function-in-c
http://www.c4learn.com/c-programs/return-multiple-values-from-function.html

How to use two parameters pointing to the same structure in one function?

I have my code below that consits of a structure, a main, and a function. The function is supposed to display two parameters that have certain values, both of which point to the same structure.
The problem I dont know how to add the SECOND parameter onto the following code :
#include<stdio.h>
#define first 500
#define sec 500
struct trial{
int f;
int r;
float what[first][sec];
};
int trialtest(trial *test);
main(){
trial test;
trialtest(&test);
}
int trialtest(trial *test){
int z,x,i;
for(i=0;i<5;i++){
printf("%f,(*test).what[z][x]);
}
return 0;
}
I need to add a new parameter test_2 there (IN THE SAME FUNCTION) using this code :
for(i=0;i<5;i++){
printf("%f,(*test_2).what[z][x]);
How does int trialtest(trial *test) changes ?
and how does it change in main ?
I know that I should declare test_2 as well, like this :
trial test,test_2;
But what about passing the address in the function ? I do not need to edit it right ?
trialtest(&test); --- This will remain the same ?
So please, tell me how would I use test_2 as a parameter pointing to the same structure as test, both in the same function..
Thank you !!
Please tell me if you need more clarification
I think that this is your homework, so I'll just write a different function that may give you an idea of what (I think) you need to do. I read that you don't want to change the trail_test parameter list, so I stuck with a similar parameter list.
struct thing {
/* put some stuff here */
};
typedef struct thing thing; /* because this is C, not C++ */
int how_many_things(thing * thing_list);
int main(void) {
int i;
thing * a;
int count_init = random(); /* let's surprise ourselves and make a random number of these */
count_init %= 128; /* but not too many or it might not work at all */
a = malloc(count_init*sizeof(things)+1);
for (i = 0; i < count_init; i++) {
thing_init(&(a[i]));
}
make_illegal_thing(&(a[count_init]) ); /* like '\0' at the end of a string */
printf("There are %i things in the list\n", how_many_things(a) );
return 0;
}
/* This is very similar to strlen */
int how_many_things(thing * a) {
int count = 0;
while (is_legal_thing(a) ) {
a++;
count++;
}
return count;
}

Resources