const array const {} - c

So you can do this:
void foo(const int * const pIntArray, const unsigned int size);
Which says that the pointer coming is read-only and the integer's it is pointing to are read-only.
You can access this inside the function like so:
blah = pIntArray[0]
You can also do the following declaration:
void foo(const int intArray[], const unsigned int size);
It is pretty much the same but you could do this:
intArray = &intArray[1];
Can I write:
void foo(const int const intArray[], const unsigned int size);
Is that correct?

No, your last variant is not correct. What you are trying to do is achieved in C99 by the following new syntax
void foo(const int intArray[const], const unsigned int size);
which is equivalent to
void foo(const int *const intArray, const unsigned int size);
That [const] syntax is specific to C99. It is not valid in C89/90.
Keep in mind that some people consider top-level cv-qualifiers on function parameters "useless", since they qualify a copy of the actual argument. I don't consider them useless at all, but personally I don't encounter too many reasons to use them in real life.

Use cdecl. It gives an error on the second entry. The first only clearly suggests that the second const refers to the *.

In C/C++, you cannot pass an entire array as an argument to a function.
You can,
however, pass to the function a pointer to an array by specifying the array's name
without an index.
(E.g)
This program fragment passes the address of i to func1() :
int main(void)
{
int i[10];
func1(i);
.
.
.
}
To receive i, a function called func1() can be defined as
void func1(int x[]) /* unsized array */
{
.
.
}
or
void func1(int *x) /* pointer */
{
.
.
}
or
void func1(int x[10]) /* sized array */
{
.
.
}
source : THE COMPLETE REFERENCE - HERBERT.

Related

function pointer with generic argument type

for knowledge sake, I would like to know if something like this is possible:
2 function:
static int func1(int *a, int b){
...
}
static int func2(double *a, int b){
...
}
I would like to declare a function pointer and point it to one of these function. However the arguments of these functions are of different type. So I tried:
static int (*func_ptr)(void *arg1, int arg2);
static void *Argument1;
static int Argument2=5;
int main(){
double arg1_d;;
int arg1_i;
...
if(want_func2){
Argument1=(double *) &arg1_d;
func_ptr=func2;
run(func_ptr);
}
else{
Argument1=(int *) &arg1_i;
func_ptr=func1;
run(func_ptr);
}
return 0;
}
static int run(int *(function)(void *,int )){
function(Argument1,Argument2);
}
However, when compiling I get the warning:
warning: assignment from incompatible pointer type
when
func_ptr=func2;
func_ptr=func1;
Is there anyway to create a function pointer with a generic type argument?
You are on the right track. But, in order to achieve what you want, your functions should have a void* parameter and cast it internally to int or double.
No. You need the if...else to use such a thing correctly anyway, so just store separate function pointers and use the correct pointer in each piece of code.

Passing a void value function as part of a function signature in C

First off I'm primarily a Java programmer, but I've been tasked with doing some network stuff in C. I've got a function with the following signature:
foo(int, void (*) (int, char *, int))
It's the void (*) that's throwing me for a loop. This is supposed to call another function (static)
bar(int, char *, int)
Now am I right in thinking that foo wants a pointer to bar with whatever variables I need at the time?
Calling
foo(1,myfunction(1,&anCharArray,10));
fails with a number of errors.
If anyone has any links to good articles on pointers that would also help.
foo(1,myfunction(1,&anCharArray,10))
fails with a number of errors.
Try instead:
foo(1, myfunction)
The second parameter of foo function is a function pointer but you were passing the return value of a function call.
The void (*)(int, char *, int) is an anonymous parameter of type 'pointer to function returning void and taking three arguments: an int, a char * and another int'. You need to pass the name of such a function (in your case, bar) as the second argument to the function foo. Personally, I'd prefer to see the declaration of foo written with a return type and names for parameters, and the declaration of bar() should also have a return type and names for the parameters. The names do not have to match between function declaration and definition, but it is not usually regarded as good style to vary the names between them.
void foo(int num, void (*func)(int num, char *str, int len));
static void bar(int num, char *str, int len);
You can then call:
foo(10, bar);
Inside foo(), you will have code such as:
void foo(int num, void (*func)(int num, char *str, int len))
{
char str[] = "Supercalifragilisticexpialidocious";
(*func)(num, str, strlen(str));
}
Or, if you're new school (not an archaic relic like me), then:
void foo(int num, void (*func)(int num, char *str, int len))
{
char str[] = "Supercalifragilisticexpialidocious";
func(num, str, strlen(str));
}
These are equivalent. I still prefer the explicit "I'm calling a function via a pointer to function" notation, but it isn't necessary and modern style tends to avoid it.

Using array from main in function ( C )

is there any way to use static array, defined in main(), in another function, without giving it to the function as a parameter?
For example:
main() has defined array:
int Array[10];
filled with integers. I'd like to create a comparing function for qsort, that has to have this header:
int compar (const void* a, const void* b);
and I would like it to decide like this:
if Array[a]<Array[b] return 1
etc...
This array cannot be given to qsort directly, but is required for exact sorting.
Also, this array has to be static (no reallocing).
Does anyone have any ideas?
The only way is, of course, so make the address of the array available as a global variable.
This is possible even if the array itself is inside main(), but you have to initialize the global to the properly scoped address, and watch the life-time, of course.
int *mains_array;
static int qsort_callback(const void *a, const void *b)
{
/* use mains_array */
}
int main(void)
{
int secret_array[100];
mains_array = secret_array;
qsort(something, something, qsort_callback);
}
It's a pretty ugly solution, it should be given more thought.
You can't access a local variable from another function. You need to make it global or file scoped.
Global:
/* Declare Array outside any function */
int Array[10];
int main(...
or, file scoped:
/* Declare Array outside any function */
static int Array[10];
int main(...
Note:
Your compare function will receive pointers to the elements to compare. If you are sorting an array of int you need to dereference the pointer in your compare function:
I'm assuming that Array isn't the array you want to sort, but an array that contains information on how to sort an array.
int compare (const void * ap, const void * bp)
{
int a = *((int*)ap);
int b = *((int*)bp);
if (Array[a] < Array[b]) {
return 1;
}
if (Array[a] > Array[b]) {
return -1;
}
return 0;
}
qsort requires the address of the array, so you don't have a choice. But where is defined the array, that does not matter. You just need to be able to refer to it.
The qsort signature is:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
So you will call it by:
qsort(Array, 10, sizeof(int), compar);
And you'll do the compare function as usual:
int compar (const void* a, const void* b) {
return *((int*)a) - *((int*)b);
}
You need to understand that the values passed to compar are not the indexes but the address of the cells of your array. So you don't have to use Array from the compar function, you already have what you need.
You're already giving him your array by calling
qsort (a, numberOfElements, sizeOfEachElement, compare);
What you need to do in your compare function is this:
int compare (const void * a, const void * b)
{
//Here int can be other type
return ( *(int*)a - *(int*)b );
}

Function Returning Itself

Is it possible to declare some function type func_t which returns that type, func_t?
In other words, is it possible for a function to return itself?
// func_t is declared as some sort of function pointer
func_t foo(void *arg)
{
return &foo;
}
Or would I have to use void * and typecasting?
No, you cannot declare recursive function types in C. Except inside a structure (or an union), it's not possible to declare a recursive type in C.
Now for the void * solution, void * is only guaranteed to hold pointers to objects and not pointers to functions. Being able to convert function pointers and void * is available only as an extension.
A possible solution with structs:
struct func_wrap
{
struct func_wrap (*func)(void);
};
struct func_wrap func_test(void)
{
struct func_wrap self;
self.func = func_test;
return self;
}
Compiling with gcc -Wall gave no warnings, but I'm not sure if this is 100% portable.
You can't cast function pointers to void* (they can be different sizes), but that's not a problem since we can cast to another function pointer type and cast it back to get the original value.
typedef void (*fun2)();
typedef fun2 (*fun1)();
fun2 rec_fun()
{
puts("Called a function");
return (fun2)rec_fun;
}
// later in code...
fun1 fp = (fun1)((fun1)rec_fun())();
fp();
Output:
Called a function
Called a function
Called a function
In other words, is it possible for a function to return itself?
It depends on what you mean by "itself"; if you mean a pointer to itself then the answer is yes! While it is not possible for a function to return its type a function can return a pointer to itself and this pointer can then be converted to the appropriate type before calling.
The details are explained in the question comp.lang.c faq: Function that can return a pointer to a function of the same type.
Check my answer for details.
Assume the function definition
T f(void)
{
return &f;
}
f() returns a value of type T, but the type of the expression &f is "pointer to function returning T". It doesn't matter what T is, the expression &f will always be of a different, incompatible type T (*)(void). Even if T is a pointer-to-function type such as Q (*)(void), the expression &f will wind up being "pointer-to-function-returning-pointer-to-function", or Q (*(*)(void))(void).
If T is an integral type that's large enough to hold a function pointer value and conversion from T (*)(void) to T and back to T (*)(void) is meaningful on your platform, you might be able to get away with something like
T f(void)
{
return (T) &f;
}
but I can think of at least a couple of situations where that won't work at all. And honestly, its utility would be extremely limited compared to using something like a lookup table.
C just wasn't designed to treat functions like any other data item, and pointers to functions aren't interchangeable with pointers to object types.
what about something like this:
typedef void* (*takesDoubleReturnsVoidPtr)(double);
void* functionB(double d)
{
printf("here is a function %f",d);
return NULL;
}
takesDoubleReturnsVoidPtr functionA()
{
return functionB;
}
int main(int argc, const char * argv[])
{
takesDoubleReturnsVoidPtr func = functionA();
func(56.7);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
typedef void *(*fptr)(int *);
void *start (int *);
void *stop (int *);
void *start (int *a) {
printf("%s\n", __func__);
return stop(a);
}
void *stop (int *a) {
printf("%s\n", __func__);
return start(a);
}
int main (void) {
int a = 10;
fptr f = start;
f(&a);
return 0;
}
It is not possible for a function to return itself by value. However it is possible itself to return by a pointer.
C allows to define function types that take undefined number of parameters and those those types are compatible with function types that take defined parameters.
For example:
typedef void fun_t();
void foo(int);
fun_t *fun = foo; // types are fine
Therefore the following function would work.
void fun(void (**ptr)()) {
*ptr = &fun;
}
And below you can find the exemplary usage:
#include <stdio.h>
void fun(void (**ptr)()) {
puts("fun() called");
*ptr = &fun;
}
int main() {
void (*fp)();
fun(&fp); /* call fun directly */
fp(&fp); /* call fun indirectly */
return 0;
}
The code compiles in pedantic mode with no warnings for C89 standard.
It produces the expected output:
fun() called
fun() called
There's a way, you just try this:
typedef void *(*FuncPtr)();
void *f() { return f; }
int main() {
FuncPtr f1 = f();
FuncPtr f2 = f1();
FuncPtr f3 = f2();
return 0;
}
If you were using C++, you could create a State object type (presuming the state machine example usage) wherein you declare an operator() that returns a State object type by reference or pointer. You can then define each state as a derived class of State that returns each appropriate other derived types from its implementation of operator().

"programming pearls": Strings of Pearls

In column 15.3, the author introduced how to generate text randomly from an input document. The author also gave the source code.
qsort(word, nword, sizeof(word[0]), sortcmp);
int sortcmp(char **p, char **q)
{ return wordncmp(*p, *q);
}
I've been confused by the above lines in the source code.
The last argument of qsort is:
int comparator ( const void * elem1, const void * elem2 ).
But the definition of sortcmp is different. Actually, the source code cannot compiled in my VS2010.
It seems this code was originally compiled with a more forgiving (or less standard-compliant) compiler. The idea seems to be that the canonical void * arguments of the comparator function are interpreted as char ** so that wordncmp(), which is an implementation of lexicographical comparison of up to length n, can be applied to them.
Declaring the function as expected (i.e. taking two const void * arguments) and making the type casts explicit appears to solve the problem (tested with GCC 4.7.0):
int sortcmp(const void *p, const void *q) {
return wordncmp(*(const char **)p, *(const char **)q);
}
I also had to modify the declaration of the wordncmp() function:
int wordncmp(const char *p, const char* q)
{
/*.. Definition unchanged.. */
}

Resources