Passing a struct to a function - c

So I am trying to pass my struct to a function and I am also trying to assign my variable to the struct, which does not seem to work. I don't know what's wrong with it either.
This is how my code looks:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ACE 1;
#define CardSize 52
#define colors 4
struct MyCards {
int *cards;
char *color[4];
};
void count(struct MyCards record);
int main() {
struct MyCards record;
count(record);
system("pause");
return 0;
}
void count(struct MyCards record) {
int i, j, f;
// I actually want to put this variable and the values into the struct, how do i do it?
char *color[4] = { "Diamon", "Heart", "Spade", "Clubs" };
record.cards = malloc(CardSize * sizeof(int));
for (f = 0; f < 4; f++) {
for (i = 0; i < 13; i++) {
record.cards[i] = (i % 13) + 1;
printf("%d of %s\n", record.cards[i], color[f]);
}
}
}
As you might see, the thing I commented out, I also want to put that variable AND the values that I have assign to it, but I dont know how to do that, would love some help there as well.

C uses pass-by-value. record inside count is a different variable to record in main - a copy is made when you call the function.
If you want main to see the changes you either need to return the changed object (in which case you wouldn't pass it in in the first place, in this example), or use pass-by-reference which you implement by passing a pointer to the object.
Returning the object would look like:
struct MyCard count(void)
{
struct myCard record;
// ... do stuff with record ...
return record;
}
Passing by reference would look like:
void count(MyCard *p_record)
{
// ... do stuff with (*p_record)
}
Also you want record.color[f] = color[f]; as the first line of the f loop. And (as discussed last time you posted about this code) you should be using string or char const *, not char *.

You have to pass a pointer to the struct in order to edit it, or you will edit the variable only in the stack of the function, which will be deleted once the function returns. Try passing &record to your function.
Also change your prototype: you have to accept a pointer to the struct.
When you have a pointer, to resolve the struct you have to use the -> operator. Let's do an example:
records->cards[i] = ...

Related

Can I pass parameters into a function if I only have a pointer to a function in C?

I have a program, what it does isn't too important, I am mostly curious of the following:
If I have a struct that has pointers to a function, can I pass parameters into the function using that pointer? Here is part of my code
edit: I realized I was a little vague:
So is there anyway to use the variable 'x' of type funcs, to pass parameters into the my_closeit and my_openit using the pointer's initialized by x = {&openit, &closeit}; in the main function? By doing x -> or x. ?
Another Edit:
Would it be x.openit(some pointer, some int); ?
#include<stdio.h>
int my_openit(char* name, int prot);
void my_closeit(void);
typedef struct funcs
{
int (*openit)(char *name, int prot);
void (*closeit)(void);
}funcs;
//I know the first 'funcs' is unnecessary
int main()
{
funcs x = {&my_openit, &my_closeit};
return 0;
}
int my_openit(char* name, int prot)
{
return 0;
}
void my_closeit(void)
{
}
can I pass parameters into the function using that pointer?
Yes, obviously, or it wouldn't be of any use. In your case:
int result = x.openit("something", 123);
Yes, just use function call expression through the pointers:
int r = x.openit("myfile",0);
x.closeit();

Container to save function pointer

I need a container to save function pointers to certain numbers.
Like
1 = function add
2 = function sub
3 = function mult
And so on. This is for a simple interrupt handler, where depending on the interrupt number a certain function should be called.
I thought that I can do this with a structured list, but I know the size of the maximal amount of entries. So I thought about an array of strings like
const char *functions[2];
a[0] = "add";
a[1] = "sub";
But then I don't know how I can further use the strings.
Any tips or thoughts?
Thanks in advance!
EDIT: To clarify, I have 2 important functions here, one, where I want to save a function pointer together with a number into some container. And another one, which just says "goto the function which is at a certain number in that container". So the first function gets an int number (say from 1 to 50) and a pointer to a function. Those should be saved together. The second function then just gets an int number as parameter and then it should call the function which is associated with that int number in my container. What I'm asking is how I could save a pointer that points to a function together with a number.
EDIT2: I do want to save function pointers. I thought I could maybe save the function name as a string and then use it later as function name because I didn't know another way.
If you want to store and use a function pointer you can do it like this:
// the functions you want to point to
int add(int a, int b) { do stuff }
int sub(int a, int b) { do some other stuff }
...
// declare and set a function pointer
int (*myFuncPtr) (int, int);
myFuncPtr = ⊂ // points to the function "sub". The & is optional
// now use it:
int result = myFuncPtr(23, 42);
The type of a function pointer depends on the return value and the parameters of the function you want to point to.
You can make the declaration of a function pointer variable easier
by using typedef:
typedef int (*funcPtr) (int, int);
Now declare and initialize a function pointer using the typedef like this:
funcPtr myFuncPtr = &add;
Of course you can now put many of those pointers into an array
and access them by the indices:
funcPtr funcPtrs[] = { &sub, add }; // like i said, the ampersand is optional
int result = funcPtrs[0](23, 42);
You have to store function pointers, so define a new function pointer type and make an array. According to your question the all functions should take two int parameters and return and int, so the new type should be something like this:
typedef int (*operation_t)(int,int);
Now you can create an array of operation_t. The whole code:
#include <stdio.h>
typedef int (*operation_t)(int,int);
int addInt(int n, int m) {
return n+m;
}
int subInt(int n, int m) {
return n-m;
}
int multipleInt(int n, int m) {
return n*m;
}
int main ()
{
const operation_t function_list[3] = {&addInt, &subInt, &multipleInt};
int i;
for(i = 0; i < 3; i++)
{
printf("inputs: 2 and 3 result: %d\n", function_list[i](2,3));
}
return 0;
}
The output:
Note that, as it's an array the indexes are 0, 1, 2.
To add an own ID you can create a stuct with the function pointer and an int ID.
typedef struct operation
{
int (*operation_p)(int,int);
int id;
} math_operation_t;
You can even build a linked list, and add functions dynamically if you define a third member variable, which should be the pointer to the next element.

How do I handle a struct component which points to an array whose size won't be known until after the struct is declared?

I have a struct with a pointer component. The pointer will point to an array whose size will be determined after the struct is declared. I will need to malloc memory and then assign it to the pointer. Somehow passing this pointer through function calls causes problems. Here is a simple example which recreates my error:
#include <stdlib.h>
#include <stdio.h>
typedef struct mystruct mystruct;
struct mystruct{
int dim;
double *dubarr;
double dub;
};
int getarr(int *dim, double *dubarr){
*dim = 2; /* The value of dim is not known until this function is called */
dubarr = malloc(*dim * sizeof(double));
double test;
int i;
for(i=0;i<*dim;i++)
{
dubarr[i] = (i+1)*7.0;
test = dubarr[i];
printf("dubarr[%i] = %.15e\n", i, test);
}
return 1;}
int initmystruct(mystruct *data){
getarr(&(data->dim),data->dubarr);
data->dub = (data->dim)*((data->dubarr)[0]);
return 1;}
int main(void){
mystruct data;
initmystruct(&data);
double test;
int i;
for(i=0;i<data.dim;i++)
{
test = (data.dubarr)[i];
printf("dubarr[%i] = %.15e\n", i, test);
}
/* I would do "free(data.dubarr);" here but it causes a crash */
return 1;}
The code compiles with no warnings but the components of data.dubarr do not maintain their values through the function calls. Here is the output:
dubarr[0] = 7.000000000000000e+00
dubarr[1] = 1.400000000000000e+01
dubarr[0] = 2.002400628035951e+176
dubarr[1] = 2.186218092030684e-154
Please point out all my mistakes :)
C uses pass by value. So here:
int getarr(int *dim, double *dubarr)
the function receives dubarr, a pointer to double, passed by value. So, whatever the function assigns to dubarr cannot be seen outside getarr. Note that the implementation of getarr modifies dubarr, but the caller will not see those modifications.
Contrast that with how you handle dim, where you modify *dim. Similarly look at the call to getarr in your code:
getarr(&(data->dim), data->dubarr);
Observe how the two arguments are treated differently. For the first argument you pass the address of a variable, for the second you pass the value of the pointer.
Instead you need:
int getarr(int *dim, double **dubarr)
And then assign to *dubarr like this:
*dubarr = malloc(...);
And call getarr like this:
getarr(&(data->dim), &(data->dubarr));

understanding how to dynamically create an array of structure and access its elements

I need to pass the address of a pointer to a structure to a function, which inturn will dynamically allocate the memory for an array of structures and fill in the values.
Now from my calling method, once i return from the func1, i should be able to iterate through the array of structure and display the value of the structure variables.
Can someone explain how to pass the address of the pointer to the structure, also iterating through the array of structures created dynamically ?
my sample code looks like this:
struct test {
int a;
int b;
};
void func1(int *n,struct test **testobj)
{
n=5;
*testobj = (struct test*) malloc(n*sizeof(struct test));
for(i=0;i<n;i++)
{
(*testobj)[i].a=1;
(*testobj)[i].b=2;
}
}
int main()
{
struct test testobj;int n;
func1(&n,&testobj);
for(i=0;i<n;i++)
{
printf("%d %d",(*testobj)[i].a,*testobj)[i].b);
}
free(testobj);
}
In main() define a pointer to a test structure:
struct test *testPtr;
To take the address of that pointer use the & address-of operator:
&testPtr;
This returns the address of the pointer and has type struct test **
You can then pass this into your function func1, which does the correct allocation (although casting malloc() is generally considered bad practice - Do I cast the result of malloc?). Other than that func1() looks good... the line...
*testobj = malloc(n*sizeof(struct test));
... is correct. *testobj dereferences your double pointer that you got by doing &testPtr, and stores the address of the new memory in your pointer. You are also correct when you dereference your double-pointer using (*testobj)[i] because [] has higher precedence than * you needed to (as you've correctly done) surround the dereference with brackets to make sure that happens before you take the index.
Thus, when func1() returns the pointer testPtr should now point to the array of n test structures you allocated and can be accessed using testPtr[i].a etc.
EDIT: Your for loop should become
for(i=0;i<n;i++)
printf("%d %d", testobj[i].a, testobj[i].b);
Your original for loop should have given you compilation errors? In the original code testobj is not a pointer, therefore dereferencing it should not be possible.
So the summary answer is in main() declare testobj as a pointer and then access the array elements as testobj[n] :)
EDIT: As eric has pointed out, remove n=5; from func1(). I think you meant *n=5 perhaps as some kind of debugging step... You probably mean to use n as the input to the function to say how many objects you want in your structure array. Either initialise n or perhaps re-define func1() to be
void func1(int n,struct test **testobj) // n is no longer a poitner, just a number
create your array of pointers to structures in declaration step itself and simply pass it to the function
struct test *testobj[10];
func1(&n,testobj);
This passes the whole array of pointers to the function
It isn't entirely clear which version you're asking for, but one of these should cover it:
/* allocate some number of tests.
*
* out_n: out parameter with array count
* returns: an array of tests
*/
struct test* allocate_some_tests(int *out_n) {
int n = 5; /* hardcoded, random or otherwise unknown to caller */
*out_n = n
struct test *t = malloc(n * sizeof(*t));
while (n--) {
t[n].a = 1;
t[n].b = 2;
}
return t;
}
/* allocate a specific number of tests.
*
* n: in parameter with desired array count
* returns: an array of tests
*/
struct test* allocate_n_tests(int n) {
struct test *t = malloc(n * sizeof(*t));
while (n--) {
t[n].a = 1;
t[n].b = 2;
}
return t;
}
Note that you can just return the allocated array, you don't need a pointer-to-pointer here.
As for calling them, and iterating over the result:
void print_tests(struct test *t, int n) {
for (; n--; t++)
printf("{%d, %d}\n", t->a, t->b);
}
int main()
{
int count1; /* I don't know how many yet */
struct test *array1 = allocate_some_tests(&count1);
print_tests(array1, count1);
int count2 = 3; /* I choose the number */
struct test *array2 = allocate_n_tests(count2);
print_tests(array2, count2);
}
Your code appears pretty much ok to me.
only edit that should make it fine is--
in place of
struct test testobj;
put the following code
struct test *testobj;
and keep the remaining as it is..!
here's the working version of what's required, here the memory is allocated in the called function just as required
#include <stdlib.h>
#include <stdio.h>
struct tests {
int a;
int b;
};
void func1(int *n,struct tests **testobj)
{
int i;
*n=5;
*testobj = (struct tests*) malloc((*n)*sizeof(struct tests));
for(i=0;i<(*n);i++)
{
(*testobj)[i].a=1;
(*testobj)[i].b=2;
}
}
int main()
{
int i;
struct tests *testobj;int n;
func1(&n,&testobj);
for(i=0;i<(n);i++)
{
printf("%d %d",(testobj)[i].a,testobj[i].b);
}
free(testobj);
}

Getting error when modifying MyType constructed using typedef in C

I create a type and try to change the int value in it.
But it keeps printing 240.
I don't know why, can anyone help me?
Here is my code:
typedef struct{
int i;
}MyType;
do(MyType mt, int ii){
mt.i = ii;
}
int main(int argc, char ** argv){
MyType mt;
do(mt, 5);
print("%d\n", mt.i);
}
Passing mt by value to function do(). Any changes made will be local to the function. Pass the address of mt:
void do_func(MtType* mt, int ii){
mt->i = ii;
}
MyType mt;
do_func(&mt, 5);
So first, your do function has some problems. You have failed to specify a return type, so int is assumed (pre-C99), but I see no reason to not just specify it. Second, do is a reserved keyword in C.
You are passing your struct by value, so a copy is made, passed to your do function, and that is modified. Everything is passed by value in C, period. Your mt variable declared in main is never touched.
Take a MyType* in your code if you need to modify one or more of its member variables, take a MyType** if you need to allocate memory for the structure itself (i.e., initialize a pointer).
// pass a pointer to the function to allow
// for changes to the member variables to be
// visible to callers of your code.
void init_mytype(MyType *mt, int ii){
if(mt)
mt->i = ii;
}
MyType mt;
init_mytype(&mt, 1);
// pass a pointer to pointer to initialize memory
// for the structure and return a valid pointer.
// remember, everything is passed by value (copy)
void init_mytype(MyType **mt, int ii) {
if(mt) {
*mt = malloc(sizeof(MyType));
if(*mt)
(*mt)->i = ii;
}
}
MyType *pmt;
init_mytype(&pmt, 1);

Resources