I'm little bit confused about how to declare a pointer to array or void*.
let say :
void* myarr[20];
how to declare a pointer to "myarr?"
I think you mean a pointer to the first element of an array of pointers to void.
It is simply to do if you will use the following general approach. Let's assume that you have an array of some type T
T myarr[20];
then the definition of the pointer to the first element of the array will look like
T *ptr = myarr;
Now all what you need is substitute T for you particulat type and you will get
void * myarr[20];
void * *ptr = myarr;
If you mean indeed a pointer to the array then approach is the following
T myarr[20];
T ( *ptr )[20] = &myarr;
Or if to substitute T for void * you will get
void * myarr[20];
void * ( *ptr )[20] = &myarr;
typedef void *myarr_t[20];
myarr_t *ptr_to_myarr;
void* (*myarr_ptr)[20] = myarr_ptr;
here is my test code:
#include <stdio.h>
int main()
{
int* myarr[20];
int * (*myarr_ptr)[20] = myarr;
printf("%p %p\n", myarr, *myarr_ptr);
return 0;
}
$ ./a.out
0x7fff8bd39dd0 0x7fff8bd39dd0
void** ptrToArrary = myarr_t; //pointing to base address of array.
Related
int main()
{
int b = 12;
void *ptr = &b;
printf("%d", *ptr);
return 0;
}
I expected for this code to print 12, but it does not.
if instead of void pointer, we define int pointer it would work.
I wanted to know how can we use void pointer and print the address allocated to it and the amount saved in it?
Dereferencing a void * doesn't make sense because it has no way of knowing the type of the memory it points to.
You would need to cast to pointer to a int * and then dereference it.
printf("%d", *((int *)ptr));
void pointers cannot be dereferenced.it will give this warning
Compiler Error: 'void' is not a pointer-to-object type*
so, you have to do it like this.
#include<stdio.h>
int main()
{
int b = 12;
void *ptr = &b;
printf("%d", *(int *)ptr);
return 0;
}
If p has type void *, then the expression *p has type void, which means "no value". You can't pass a void expression to printf for the %d conversion specifier (or any other conversion specifier).
In order to dereference a void *, you must first convert it to a pointer of the appropriate type. You can do it with a cast:
printf( "%d\n", *(int *) ptr );
or assign it to a pointer of the appropriate type:
int *p = ptr;
printf( "%d\n", *p );
The rules around void pointers are special such that they can be assigned to other pointer types without an explicit cast - this allows them to be used as a "generic" pointer type. However, you cannot directly examine the thing a void pointer points to.
A schoolbook example of when void pointers are useful is qsort.
This is the signature:
void qsort(void *base,
size_t nitems,
size_t size,
int (*compar)(const void *, const void*)
);
base is just a pointer to the first element. The reason it's a void pointer is because qsort can be used for any list, regardless of type. nitems is number of items (doh) in the list, and size is the size of each element. Nothing strange so far.
But it does also take a fourth argument, which is a function pointer. You're supposed to write a custom compare function and pass a pointer to this function. This is what makes qsort able to sort any list. But since it's supposed to be generic, it takes two void pointers as argument. Here is an example of such a compare function, which is a bit bloated for clarity:
int cmpfloat(const void *a, const void *b) {
const float *aa = (float*) a;
const float *bb = (float*) b;
if(*aa == *bb) {
return 0;
} else if(*aa > *bb) {
return 1;
} else {
return -1;
}
}
Pretty clear what is going on. It returns positive number if a>b, zero if they are equal and negative if b>a, which is the requirements. In reality, I'd just write it like this:
int cmpfloat(const void *a, const void *b) {
return *(float*)a - *(float*)b;
}
What you do with this is something like:
float arr[5] = {5.1, 3.4, 8.9, 3.4, 1.3};
qsort(arr, 5, sizeof *arr, cmpfloat);
Maybe it's not completely accurate to say that void pointers are used instead of templates, generic functions, overloaded functions and such, but they have similarities.
I would like to convert a int pointer to a void pointer and pass that void pointer to a function and then back to an int pointer to use that value in another function.
void main(){
int newSize = size;
void *newSizePtr = &newSize;
someFunc(newSizePtr);
}
void someFunc(void *newSizePtr){
int actualValue = *((int *) newSizePtr);
}
Is this the right way to convert a int ptr to a void ptr and then back to use the value?
i am unable to dynamically allocate memory to the pointer itself because of restrictions with my program that i cannot use malloc. i.e.
int *newSize = malloc(sizeof(int));
which is why i did it this way.
i also need to pass in a void* argument because in my program i am using pthread_create(). This function requires me to pass in an argument of a void* to the function which is why i casted it to a void* and then back when i needed to use it
The conversion you are doing is explicitly allowed by the C standard. Section 6.3.2.3p1 regarding pointer conversions states:
A pointer to void may be converted to or from a pointer to any
object type. A pointer toa ny object type may be converted to a
pointer to void and back again; the result shall compare equal
to the original pointer.
It's also not necessary to explictily cast to or from a void *. So you can do something like this:
void someFunc(void *newSizePtr){
int *actualValuePtr = newSizePtr;
}
int main(){
int newSize = size;
pthread_t tid;
pthread_create(&tid, NULL, someFunc, &newSize);
}
#include <stdio.h>
#include <memory>
void someFunc(void*);
int main() {
int size = 4;
int newSize = size;
void* newSizePtr = &newSize;
someFunc(newSizePtr);
// void* -> int*, before using
int* newSize = (int*) malloc(sizeof(int));
}
void someFunc(void* newSizePtr) {
int actualValue = *((int*)newSizePtr);
printf("%d", actualValue);
}
Yes you can cast void* to int*, and int* to void *,
Because, void * is 'generic' pointer.
malloc returns generic pointer (void*) because malloc does not know what 'type' of return you need.
So, you need to convert to the type you need.
(In the above code, you need to convert to void* -> int*)
For more information about usage of generic pointer, below link may help you
https://codexpart.com/what-is-generic-pointer-difference-between-generic-pointer-and-void-pointer/
I've a little question.
I'm trying to define an array of function pointers dynamically with calloc.
But I don't know how to write the syntax.
Thanks a lot.
The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to:
int foo( int )
would be:
int (*)( int )
In order to name an instance of this type, put the name inside (*), after the star, so:
int (*foo_ptr)( int )
declares a variable called foo_ptr that points to a function of this type.
Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so:
int (*foo_ptr_array[2])( int )
declares a variable called foo_ptr_array which is an array of 2 function pointers.
The syntax can get pretty messy, so it's often easier to make a typedef to the function pointer and then declare an array of those instead:
typedef int (*foo_ptr_t)( int );
foo_ptr_t foo_ptr_array[2];
In either sample you can do things like:
int f1( int );
int f2( int );
foo_ptr_array[0] = f1;
foo_ptr_array[1] = f2;
foo_ptr_array[0]( 1 );
Finally, you can dynamically allocate an array with either of:
int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) );
foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) );
Notice the extra * in the first line to declare a1 as a pointer to the function pointer.
I put a small example here that may help you
typedef void (*fp)(int); //Declares a type of a void function that accepts an int
void test(int i)
{
printf("%d", i);
}
int _tmain(int argc, _TCHAR* argv[])
{
fp function_array[10]; //declares the array
function_array[0] = test; //assings a function that implements that signature in the first position
function_array[0](10); //call the cuntion passing 10
}
You'd declare an array of function pointers as
T (*afp[N])();
for some type T. Since you're dynamically allocating the array, you'd do something like
T (**pfp)() = calloc(num_elements, sizeof *pfp);
or
T (**pfp)() = malloc(num_elements * sizeof *pfp);
You'd then call each function as
T x = (*pfp[i])();
or
T x = pfp[i](); // pfp[i] is implicitly dereferenced
If you want to be unorthodox, you can declare a pointer to an array of pointers to functions, and then allocate that as follows:
T (*(*pafp)[N])() = malloc(sizeof *pafp);
although you would have to deference the array pointer when making the call:
x = (*(*pafp)[i])();
typedef R (*fptr)(A1, A2... An);
where R is the return type, A1, A2... An are the argument types.
fptr* arr = calloc(num_of_elements,sizeof(fptr));
Assuming all your functions are of type void ()(void), something like this
typedef void (*fxptr)(void);
fxptr *ptr; // pointer to function pointer
ptr = malloc(100 * sizeof *ptr);
if (ptr) {
ptr[0] = fx0;
ptr[1] = fx1;
/* ... */
ptr[99] = fx100;
/* use "dynamic array" of function pointers */
free(ptr);
}
I'm beginning to learn C and read following code:
public void** list_to_array(List* thiz){
int size = list_size(thiz);
void **array = malloc2(sizeof(void *) * size);
int i=0;
list_rewind(thiz);
for(i=0; i<size; i++){
array[i] = list_next(thiz);
}
list_rewind(thiz);
return array;
}
I don't understand the meaning of void**. Could someone explain it with some examples?
void** is a pointer to a pointer to void (unspecified type). It means that the variable (memory location) contains an address to a memory location, that contains an address to another memory location, and what is stored there is not specified. In this question's case it is a pointer to an array of void* pointers.
Sidenote: A void pointer can't be dereferenced, but a void** can.
void *a[100];
void **aa = a;
By doing this one should be able to do e.g. aa[17] to get at the 18th element of the array a.
To understand such declarations you can use this tool and might as well check a related question or two.
void** is a pointer to void*, or a pointer to a void pointer if you prefer!
This notation is traditionally used in C to implement a matrix, for example. So, in the matrix case, that would be a pointer to an array of pointers.
Normally void * pointers are used to denote a pointer to an unknown data type. In this case your function returns an array of such pointers thus the double star.
In C, a pointer is often used to reference an array. Eg the following assignment is perfectly legal:
char str1[10];
char *str2 = str1;
Now when void is used, it means that instead of char you have a variable of unknown type.
Pointers to an unknown data type are useful for writing generic algorithms. Eg. the qsort function in standard C library is defined as:
void qsort ( void * base,
size_t num,
size_t size,
int ( * comparator )
( const void *, const void * ) );
The sorting algorithm itself is generic, but has no knowledge of the contents of the data. Thus the user has to provide an implementation of a comparator that can deal with it. The algorithm will call the comparator with two pointers to the elements to be compared. These pointers are of void * type, because there is now information about the type of data being sorted.
Take a look at this thread for more examples
http://forums.fedoraforum.org/showthread.php?t=138213
void pointers are used to hold address of any data type. void** means pointer to void pointer. Void pointers are used in a place where we want a function should receive different types of data as function argument. Please check the below example
void func_for_int(void *int_arg)
{
int *ptr = (int *)int_arg;
//some code
}
void func_for_char(void *char_arg)
{
char *ptr = (char *)char_arg;
//some code
}
int common_func(void * arg, void (*func)(void *arg))
{
func(arg);
}
int main()
{
int a = 10;
char b = 5;
common_func((void *)&a, func_for_int);
common_func((void *)&b, func_for_char);
return 0;
}
I am trying to use a double void pointer but I am a little bit confused about the usage.
I have a struct that contains a void ** array.
struct Thing{
void ** array;
};
struct Thing * c = malloc (sizeof(struct Thing));
c->array = malloc( 10 * sizeof(void *) );
So If I want to assign a different object to each pointer and try to retrieve the value
// Option 1
*(c->array + index) = (void *) some_object_ptr;
// Option 2
c->array[index] = (void *) some_object_ptr;
then, I have another function that gives (void *) item that points to each cell, not the some_object_ptr.
If I want to retrieve the value which pointed to by some_object_ptr,
should I do
function return type is 'void *' and takes argument 'void *'
// Option 3
return (void**) item
// Option 4
return *((void**)item)?
the weird thing is that when I used array the array subscript method I couldn't use option 4, only option 3; and when I used *(c->array + index) I could only use opt.4. and not opt.3. ..
Can anyone please tell me about this? If I am making any invalid assumptions, then could you please correct me?
A void ** is just a pointer to a pointer to memory with an unspecified type. You can only dereference it once (since you can't dereference a void *). However, apart from that, it is basically like any other pointer type. If it helps you, think of it the same way as you would with int *.
So, in your specific situation, we have:
void** array;
int arrayLen = 10;
array = (void**)malloc(arrayLen * sizeof(void*));
some_type_t* some_object_ptr;
// The following two assignment are equivalent since in C,
// array[index] <=> *(array + index)
array[index] = (void*)some_object_ptr;
*(array + index) = (void*)some_object_ptr;
Then array is a pointer to the whole array, while *array is a pointer to the first element, since it is equivalent to array[0].
One quick hint about pointers: if you are casting it, you are probably doing something wrong.
As for your question. I am not sure what item is in your problem. In your first part you've already discovered how to acces a member in your array. You could simply use it:
void *get_item(Thing *c, int index)
{
return *(c->array + index); // or return c->array[index];
}
If you need the address of the pointer at index:
void **get_item_cell(Thing *c, int index)
{
return c->array + index; // or return &c->array[index];
}
In the second part, you don't dereference the pointer (for + option), or take the address of array result, since it automatically dereferences it.
EDIT:
I think I now know what you want. You have a function similar to my second one above, but it is:
void *get_item_cell(Thing *c, int index)
{
return (void *)(c->array + index);
}
You want to dereference the value returned from this function, and access the object. In that case, you can only use Option 4 safely. Since you don't have the index, you cannot move to any other cell (you don't know if you are at the end of the array, or at the beginning - so no additions or subtractions). You can only fix the mistake of the above function: cast to void **, and then dereference it: *(void **)item. This will give you a void *. If you want to access the object pointed from this cell, you need to cast that to the correct type as well: some_object_ptr *obj = *(void**)item.
The fact you are working with void* and void** doesn't matter, pointer arithmetic still works fine, so both options you wrote are correct.
Here's an example:
struct Thing
{
void ** array;
};
struct Object
{
int i;
char c;
};
int main ()
{
struct Thing * c = malloc (sizeof(struct Thing));
c->array = malloc(10 * sizeof(void*));
struct Object * o = malloc (sizeof(struct Object));
o->i = 2; o->c = 'a';
*(c->array + 2) = o;
printf("Object: i = %d, c = %c\n", ((Object*)c->array[2])->i, ((Object*)c->array[2])->c);
free(o);
free(c->array);
free(c);
return 0;
}
Since it's void* you can put there pointer to whatever, just don't forget it to cast to original type before using it ;)
Almighty push!
any_type x ;
void * v = * ( void * * ) & x ;
almighty pull!
void * v ;
any_type x = * ( any_type * ) & v ;
beware of losing/gaining digits