C Function Prototype With Struct Argument - c

I want to write a function prototype for a function, whose argument is a pointer to a struct.
int mult(struct Numbers *n)
However, the struct Numbers, which is defined as
struct Numbers {
int a;
int b;
int c;
};
is not defined yet. How should I write a suitable prototype for mult?

Just declare struct Numbers as an incomplete type before your function declaration:
struct Numbers;
int mult(struct Numbers *n);

You must forward the declaration of the structure to tell the compiler that a struct with that name will be defined:
struct Numbers;
int mult(struct Numbers *n) {
}
struct Numbers {
int a;
int b;
int c;
};
Mind that the compiler is not able to determine the size in memory of the structure so you can't pass it by value.

Related

Struct with pointer to function

can you please explain in details this line of code inside struct:
There is a pointer to function but why would you reference it to struct?
void (*function)(struct Structure *);
what does this mean
(struct Structure *)?
(struct Structure *)
It means that the function have a struct Structure * argument. Actually it will make more sense with (struct Structure *variable of struct).
In this way, you can use a pointer to point a struct and should put the address of the struct variable which can be used in the function.
#include <stdio.h>
typedef struct circle{
int rad;
int area;
} Circle;
void ShowCircleInfo(Circle *info)
{
printf("rad value: %d\n", info->rad);
printf("area value: %d", info->area);
}
int main(void)
{
Circle circle_one;
circle_one.rad = 2;
circle_one.area = 3;
ShowCircleInfo(&circle_one);
return 0;
}
void (*function)(struct Structure *); declares function to be a pointer to a function that has a parameter of type struct Structure * and does not return a value.
For example
#include <stdio.h>
struct Structure {
int a;
void (*function)(struct Structure *);
};
void foo(struct Structure *a) {
if (a->function == NULL) a->function = foo;
a->a++;
printf("%d\n", a->a);
}
int main(void) {
struct Structure a = {42, foo};
struct Structure b = {0}; // don't call b.function just yet!!
a.function(&b); // foo(&b)
b.function(&a); // foo(&a)
}
See code running at https://ideone.com/7E74gb
In C, function pointer declarations have almost the same structure as function headers.
Only the function name will change to have some parantheses and a "*" in it, and the arguments won't have names, because only their types are important when using pointers (we don't access the values of the arguments, so we don't need their names).
They basically look like this:
<return_value> (*<function_name>)(<argument_list>)
So, for example, the function pointer for the function
void swap(int* a, int* b);
would be
void (*swap_ptr)(int*, int*);
Notice that the name of the pointer is in the place of the name of the function, and looks a bit odd compared to normal pointer declarations.
An excellent reading on this topic (you can skip the C++ stuff): https://www.cprogramming.com/tutorial/function-pointers.html

How to set the argument of a function pointer of type its parent structure

I try to define function pointers as the members of the structure which can access and modify other parameters of the structure (like functions of a class in OOP).
For this, I have a structure with two function pointers:
typedef struct{
int a;
int b;
int (*init)(); // line 4
int (*multiply)(); // line 5
}STR_X2;
where the function pointers are defined as follows:
void init(STR_X2* self , int _a , int _b){
self->a = _a;
self->b = _b;
printf("Init a:%d, b:%d \n",self->a,self->b);
}
int multiply(STR_X2* self){
printf("Multiply a:%d, b:%d, res:%d\n",self->a,self->b,self->a*self->b);
return self->a*self->b;
}
and then I use the structure in main() function as follows:
int main(void) {
STR_X2* val2;
val2->init = init;
val2->multiply = multiply;
val2->init(val2,7,5);
printf("result:%d\n",val2->multiply(val2));
return EXIT_SUCCESS;
}
both function pointers have one argoment of type STR_X2. But logically I cannot define this argument because the structure STR_X2is not defined at line 4 and 5. My question: Is this way of defining function pointer (without argument) safe?Is there any better alternative to access the structure member in such function pointers?
Basically what you want here is a forward declaration of a structure type. You can achieve this by using structure tags. For example:
typedef struct STR_X2_S STR_X2;
struct STR_X2_S {
int a;
int b;
int (*init)(STR_X2 *self, int _a, int _b);
int (*multiply)(STR_X2 *self);
};

How can I create a struct with a vTable or array of function pointers in C?

I am having a problem with declaring a struct with an array of function pointers (vTable) in C because if I declare the function pointer first and a parameter needs to be a self-referencial "this" pointer to itself, the struct hasn't yet been declared. If I declare the function pointer AFTER the struct, then the function type hasn't been declared so the compiler complains when I set up the struct:
#include <stdio.h>
#include <stdlib.h>
typedef int (*math_operation) (struct _MyClass *this,int a, int b);
typedef struct _MyClass{
int number;
char name[50];
math_operation *vTable[50];
} MyClass;
int main(void)
{
MyClass *test;
return(EXIT_SUCCESS);
}
What is the proper way to create an array of function pointer which have a "this" pointer to the parent struct?
You just need a forward declaration of the struct in the global namespace:
struct MyClass_;
typedef int math_operation(struct MyClass_ *this, int a, int b);
typedef struct MyClass_{
int number;
char name[50];
math_operation *vTable[50];
} MyClass;
Things to note:
I fixed the tag identifier, so it won't tread on the C standard.
I changed the function pointer typedef into a function type typedef. You already defined vTable as an array of pointers to math_operation. One pointer declarator was superfluous. This also has the nice utility of allowing you to declare functions by their intended purpose, and have the compiler type check it:
math_operation add;
// .. Later
int add(struct MyClass_ *this, int a, int b) {
return a + b;
}

Nested struct in C issue

I have a struct declaration in C that looks something like this:
static struct {
int a;
int b;
} myStruct[10];
I want to declare a struct member variable inside myStruct, so I try to add this:
static struct {
int c;
int d;
struct myStruct[10] s;
} myNestedStruct[100];
I'm getting a bunch of errors i.e. syntax error before or at: [ and
syntax requires ";" after last struct/union member. What would the better way to implement the nested structs be?
EDIT: My code now looks like this:
static struct {
int a;
int b;
} myStruct[10];
static struct {
int c;
int d;
struct myStruct s[10];
} myNestedStruct[100];
However I'm getting an error: incomplete struct/union/enum myStruct: s
You need to declare myStruct first before using it as a struct type.
struct myStruct {
int a;
int b;
};
static struct {
int c;
int d;
struct myStruct s[10];
} myNestedStruct[100];
This creates a variable called myNestedStruct which is an array of 100 structs, each containing two ints and an array of 10 mystructs.
When you write code like
struct { ... } Foo;, it's not declaring a type named Foo but a variable. Its type is an anonymous struct corresponding to what you put in the curly braces. If you want to declare a type, write struct Foo { ... };.
That's where your error is coming from -- myStruct is not a type name, so when you write struct myStruct in the definition of myNestedStruct the compiler thinks you're about to define a struct by that name. But then it encounters an [ which shouldn't be the next token in a struct declaration ever so it tells you can't make sense of the code.

Pass a struct to pthread_create's startup routine

So I've got an assignment that I'm having trouble with. I'm trying use pthreads to sum the elements of a matrix with 3 different processors. I have a struct
typedef struct{
int rows;
int cols;
pid;
int localsum;
}ThreadData;
some global variabls
int processors=3;
int rows=4;
int cols=4;
int matrix[10][10];
and a sum function
void *matrixSum(void *p){
//cast *a to struct ThreadData?
int sum=0;
int i=p->pid;
int size=p->rows*p->cols;
//to sequentially add a processor's 'owned' cells
int row=p-pid/p-cols;
int col=p-pid%p->cols;
int max_partition_size = ((size/processors)+1);
for(i;i<max_partition_size*processors;i+=processors){
col=i%p->cols;
row=i/p->cols;
if(i<=size-1){
sum+=matrix[row][col]+1;
}
}
p->localsum=sum;
}
so my main method looks like this:
int main(){
int totalsum=0;
ThreadData *a;
a=malloc(processors*(sizeof(ThreadData));
int i;
for(i=0;i<processors;i++){
a[i].rows=rows;
a[i].cols=cols;
a[i].pid=i;
a[i].localsum=0;
}
//just a function that iterates over the matrix to assign it some contents
fillmatrix(rows, cols);
pthread_t tid[processors];
for(i=0;i<processors;i++){
pthread_create(tid,NULL,matrixSum,(void *)&a);
totalsum+=a[i].localsum;
}
pthread_join();
}
My ultimate goal is to pass my matrixSum() with a ThreadData struct as the argument.
So I think I have to cast the void pointer given in matrixSum() to a struct, but I'm having trouble doing so.
I tried doing so like this
ThreadData *a=malloc(sizeof(ThreadData));
a=(struct ThreadData*)p;
But I get a warning: assignment from incompatible pointer type error.
So what's the proper way to do this - that is to cast the void pointer taken from the parameters, and operate on it like the struct it is meant to be?
Try using a=(ThreadData*)p;.
In C language, struct ThreadData is differ to ThreadData.
In this case, you used typedef and defined no tag to the struct, so you mustn't use struct to use the struct.

Resources