Define a function pointer to be32toh() function - c

I'm newly learned about function pointers here but I couldn't define a function pointer to be32toh() or other functions of endian.h header.
First of all, I can do what is told in the given thread:
#include <endian.h>
int addInt(int n, int m) {
return n+m;
}
int main(){
int (*functionPtr)(int,int);
functionPtr = addInt;
return 0;
}
But when I try to do the same for a function like be32toh(), I'll get a compilation error:
#include <stdint.h>
#include <endian.h>
int addInt(int n, int m) {
return n+m;
}
int main(){
int (*functionPtr)(int,int);
functionPtr = addInt;
uint32_t (*newptr)(uint32_t);
newptr = &be32toh;
return 0;
}
Compile as:
$ gcc test.c
Result is as below:
test.c: In function ‘main’:
test.c:15:15: error: ‘be32toh’ undeclared (first use in this function)
15 | newptr = &be32toh;
| ^~~~~~~
test.c:15:15: note: each undeclared identifier is reported only once for each function it appears in
What's the problem and how to fix it?

What's the problem
be32toh is a macro.
how to fix it?
Just write the function yourself.
uint32_t be32toh_func(uint32_t a) {
return be32toh(a);
}
....
newptr = &be32toh_func;

Related

Is there a way to declare the variables a and b in this code?

i am trying to call a function in main so that my code will execute through all parts of my code. Now when i call for compare_quads in main. i am getting an error code of a and b not being declared. but my problem is that i do not know how to get the variable declared because i have declared the function and variable at the top of the code i thought that would work. and if i try declaring the variable in main like
const void *a;
const void *b;
then when compiling i receive, warning a is used uninitialized in this function, and similarly with b.
here is my code,
//declare libraries
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//declare other functions/files to be used in the program
void print_fun(void);
void read_fun(void);
static int compare(int arg, unsigned char networks[arg][4]);
int compare_quads(const void *a, const void *b);
//read command line input and store the information
int main(int argc, char** argv){
//declar variable
int arg = 0;
//make argv into an int
arg = atoi(argv[1]);
//assign size to networks
unsigned char networks[arg][4];
//assign input to networks
for (int j =0; j<1; ++j){
if(argc == 1)
{
printf("ERROR ERROR, you messed up\n");
}
else
{
// hold network addresses in a 2-d array, with 4 unsigned char
for(int k = 0; k<arg; k++){
for (int i =0; i<4; i++){
scanf("%hhu.", &networks[k][i]);
//checks to see if scanf was working properly
// printf(" %hhu",networks[k][i]);
}
//printf("\n");
}}}
compare_quads(a, b);
compare(arg, networks);
return(0);
}
int compare_quads( const void *a, const void *b) {
return memcmp (a, b, 4);
}
static int compare(int arg, unsigned char networks[arg][4])
{
qsort(networks, arg, sizeof(networks[0]), compare_quads);
for (int k = 0; k< arg; k++){
printf("%d.%d.%d.%d\n", networks[k][0],networks[k][1],networks[k][2],networks[k][3]);
}
return 0;
}
I am pretty new to c, so please let me know if you need any clarification. thank you.
the exact warnings are
unitilazed
main.c: In function ‘main’:
main.c:47:19: error: ‘a’ undeclared (first use in this function)
47 | compare_quads(a, b);
| ^
main.c:47:19: note: each undeclared identifier is reported only once for each function it appears in
main.c:47:22: error: ‘b’ undeclared (first use in this function)
47 | compare_quads(a, b);
| ^
when const void *a; is used to initalize.
main.c: In function ‘main’:
main.c:48:5: warning: ‘a’ is used uninitialized in this function [-Wuninitialized]
48 | compare_quads(a, b);
| ^~~~~~~~~~~~~~~~~~~
main.c:48:5: warning: ‘b’ is used uninitialized in this function [-Wuninitialized]
EDIT
I am taking in one input file that has, a various amount of lines with network address like
139.72.16.202
i am storing the values in an array of size [variable that is set by arg][4]
then after the main function the rest i am using to sort the code by column. the sorting function worked fine.
A pointer to the compare_quads function is getting passed to the qsort function as a comparison function, so it will get called internally by qsort.
Because of this, you don't need to call compare_quads in your main function. Passing it to qsort is enough.

Error while implementing a complex construct in C < char (*(*f())[]) () >

Error while implementing a complex construct in C.
Here is the piece of snippet I had tried.
'Where f is a function returning a pointer to an array of
pointers pointing to a function returning character.'
#include <stdio.h>
int main()
{
char (*(*f())[]) ();
char s ()
{
return 'y';
}
char (*g[1])();
g[0] = s;
printf("%c\n",g[0]());
// here it's throwing error how to fix it?**strong text**
(char (*(*)[])()) func()
{
return g;
}
f = func;
printf("%c\n",(f())[0]());
return 0;
}
Error:
enter code heremain.c: In function ‘main’:
main.c:27:19: warning: implicit declaration of function ‘func’ [-Wimplicit-function-declaration]
(char (*(*)[])()) func()
^~~~
main.c:27:1: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
(char (*(*)[])()) func()
^
main.c:28:1: error: expected ‘;’ before ‘{’ token
{
^
main.c:33:1: error: invalid use of array with unspecified bounds
printf("%c\n",(f())[0]());
^~~~~~
main.c:33:16: error: called object is not a function or function pointer
printf("%c\n",(f())[0]());
Use typedefs to help:
#include <stdio.h>
typedef char (*functionPtr)(void);
typedef char (**arrayOfFunctionPtr)(void);
// OR THIS
// typedef functionPtr* arrayOfFunctionPtr;
typedef arrayOfFunctionPtr (*functionReturningArrayOfFunctionPointers)(void);
int main()
{
functionReturningArrayOfFunctionPointers f;
char s()
{
return 'y';
}
char (*g[1])();
g[0] = s;
printf("%c\n",g[0]());
arrayOfFunctionPtr func()
{
return g;
}
f = func;
printf("%c\n",(f())[0]());
return 0;
}

expected declaration specifier error , when declaring an external stack

There are three files :
test.c
#include "stack.h"
stackT s2;
StackInit(&s2, 15);
int main(){
stackT s1;
StackInit(&s1, 10);
StackDestroy(&s1);
return 0;
}
stack.h
typedef char stackElementT;
typedef struct {
stackElementT *contents;
int top;
int maxSize;
} stackT;
void StackInit(stackT *stackP, int maxSize);
void StackDestroy(stackT *stackP);
stack.c
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void StackInit(stackT *stackP, int maxSize)
{
stackElementT *newContents;
newContents = (stackElementT *)malloc(sizeof(stackElementT) * maxSize);
if (newContents == NULL) {
fprintf(stderr, "Insufficient memory to initialize stack.\n");
exit(1);
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1;
}
void StackDestroy(stackT *stackP)
{
free(stackP->contents);
stackP->contents = NULL;
stackP->maxSize = 0;
stackP->top = -1;
}
I really need to have an external stack and
stackT s2;
StackInit(&s2, 15);
in test.c is my attempt to declare that but compiler gives the following error.
test.c:4:11: error: expected declaration specifiers or ‘...’ before ‘&’ token
StackInit(&s2, 15);
^
test.c:4:16: error: expected declaration specifiers or ‘...’ before numeric constant
StackInit(&s2, 15);
^~
Here is what I have tried:
I declared stack s1 inside the main function and didn't get any errors for that.
I deleted #include "stack.h" in test.c and I got
the same error for the external stack s2.
So my questions are:
What is the error for? How can I declare the external stack without any errors?
You can't call functions at top-level in C, you can only have declarations and definitions. Move the call to StackInit() into the main() function.
#include "stack.h"
stackT s2;
int main(){
stackT s1;
StackInit(&s1, 10);
StackInit(&s2, 15);
StackDestroy(&s1);
StackDestroy(&s2);
return 0;
}
A function can only be called from another function. Imagine functions call like a tree in which the root node is the main() function.
Anyway, besides moving the initialization inside main(), if you really want the struct variable definition outside main you can statically initialize it, just doing what StackInit() would do: a stackElementT array of size 15, contents field pointing to the first element, and the top index initialized to -1.
#include "stack.h"
stackElementT elements[15];
stackT s2 = { elements, -1, 15};
int main(){
stackT s1;
StackInit(&s1, 10);
StackDestroy(&s1);
return 0;
}

Flexible array in C

Im trying to have an unlimited array in C to store some data. My header file stock.h looks like this
#ifndef STOCK_H
#define STOCK_H
typedef struct {
char* id;
char* descripcion;
int precio;
} tAppliance;
typedef struct {
int cantidad;
tAppliance electrodomestico;
} tElectroStock;
typedef struct {
int size;
int capacity;
tElectroStock *electrodomesticos;
} tStock;
void tstock_init(tStock *stock);
void tstock_add(tStock *stock, tAppliance item, int cantidad);
#endif
My stock.c file
#include <stdio.h>
#include "stock.h"
void tstock_init(tStock *stock) {
stock->size = 0;
stock->capacity = 10;
stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
}
void tstock_add(tStock *stock, tAppliance item, int cantidad) {
if(stock->size >= stock->capacity) {
stock->capacity = stock->capacity * 2;
stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
}
tElectroStock t;
t.cantidad = cantidad;
t.electrodomestico = item;
stock->size++;
stock->electrodomesticos[stock->size] = t;
}
And finally my main function
#include <stdio.h>
#include "stock.h"
int main(int argc, char **argv)
{
tStock t; // Creamos nuestra variable de stock
tstock_init(&t); // Iniciamos el stock
tAppliance item;
item.descripcion = "Television SONY";
item.id = "apeid9";
item.precio = 20;
tstock_add(&t, item, 1);
tstock_add(&t, item, 1);
}
As you can see on my main function I try to add 2 items to tStock. however adding the second item seems to crash the whole applicattion and no idea why.
Enable all warnings, and treat every single one of them as error. That way you could've found the issue with the member not being a pointer that's already been mentioned yourself.
Check the return value of library functions like malloc and realloc for errors and handle them appropriately.
Finally, you'll want to swap these two lines:
stock->size++;
stock->electrodomesticos[stock->size] = t;
Compile with -Wall you'll be warn:
test.c: In function ‘tstock_init’:
test.c:634:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
^
test.c:634:32: warning: incompatible implicit declaration of built-in function ‘malloc’
stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
^
test.c: In function ‘tstock_add’:
test.c:640:9: warning: implicit declaration of function ‘realloc’ [-Wimplicit-function-declaration]
stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
^
test.c:640:36: warning: incompatible implicit declaration of built-in function ‘realloc’
stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
Add to stock.c:
#include <stdlib.h>
You must also switch instruction as below:
stock->electrodomesticos[stock->size] = t;
stock->size++;
Otherwise your code is UB when stock->size++ == stock->capacity

Why does C give this error ‘size’ undeclared (first use in this function)?

I am a beginner of c programming. I can to write my own malloc function and I put main method code one. It gives following error.
test.c: In function ‘main’:
test.c:38:30: error: ‘size’ undeclared (first use in this function)
test.c:38:30: note: each undeclared identifier is reported only once for each function it appears in
code
/*An horrible dummy malloc*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void *malloc(size_t size);
void *malloc(size_t size){
void *p;
p = sbrk(0);
//if sbrk dails , we return null
if(sbrk(size)==(void*)-1){
return NULL;
}
printf("wada\n");
return p;
}
typedef struct s_block *t_block;
struct s_block{
size_t size;
t_block next;
int free;
};
int main(){
malloc(50);
malloc(100);
t_block b;
b = sbrk(0);
sbrk(sizeof(struct s_block)+size);//Error line (code 1)
b->size = size; //Error Line
return 0;
}
In this line: sbrk(sizeof(struct s_block)+size) you use a variable size that you have not defined anywhere. This is clearly stated in the error message.
BTW you should call your function something instead of malloc.

Resources