简体   繁体   中英

Self casting a void pointer to point to int in C program is it possible?

I was writing a program to dynamically generate arrays, just as an experiment to clear off rust , still a student and havent been doing C code for a while: See the block which is marked with "WORKING" comment in code below.

Constraint : you have only one void pointer to point to user requested/generated type array(the array can be a float, int, double, char)
you do not get to create pointers of any other type in main routine.

Is it possible to self cast a void pointer to (int *)

Here is some weird code:

#include <stdio.h>
#include <stdlib.h>

//prototypes
int* create_int_arr(int);

int main()
{
    int choice, arr_size;
    void* arr_ptr;
    printf("Please enter what kind of array you want?");
    printf("\nOptions are :");
    printf("\n1: int 2:float 3:char 4:double");
    scanf("%d",&choice );
    printf("\nHow many elements in the array do you want?");
    scanf("%d",&arr_size);
    switch(choice){
        case 1: printf("\nYou have chosen Integer array");
            arr_ptr =(int *) create_int_arr(arr_size);
            printf("\nThe array starts at %p",arr_ptr);
            break;
        case 2: printf("\nYou have chosen Float array");
            //create_float_arr();
            break;
        case 3: printf("\nYou have chosen a char array");
            //create_char_arr();
            break;
        case 4: printf("\nYou have chosen a double array");
            //create_double_arr();
            break;
        default:printf("\nYou have not chosen properly! Exiting!");
            return 0;
            break;
    }
    //arr_ptr = (int *)arr_ptr    <= does nothing FAIL! self cast
    int i;
    for(i=0;i<arr_size;i++)
    {
        //==========WORKING =============
        *(int*)arr_ptr = i;           //casting the void pointer to int to store values every time, would like to self cast the void pointer to int* permanently any way to do this?
                  //i know i can declare a new int pointer and cast the void* into int* but lets just say that was not an option for arguments sake

        printf("\n%d", *(int *)arr_ptr);
        //=================================
    }

    return 0;
}

int* create_int_arr(int size){
    int * ptr = malloc(sizeof(int)*size);
    printf("\nThe array starts at %p",ptr);
    return ptr;
} 

Help me out pro ppl at C! :)

Yes void pointer can be typecasted.

While your are tying to assign & print the value, the base address is not incremented. Find the correction here

*(int*)(arr_ptr+i) = i; 
printf("\n%d", *(int *)(arr_ptr+i));

arr_ptr is a pointer, which holds only the base address.In your case, traverses from base address and assign the value.

Your function already returns a int* , so just change the type of your pointer to int* and delete all the casts. A good C program should not contain casts but chose the right type for all variables from the start.

Then, effectively as mahendiran says, the for -loop is probably not what you want it to do. Just use arr_ptr[i] = i; to write i in the i th place of the array.

The casting in your program is not correct. malloc() returns a void * pointer which needs to be cast to int * as shown below.

int* create_int_arr(int size){
            int * ptr = (int *)malloc(sizeof(int)*size);
            printf("\nThe array starts at %p",ptr);
            return ptr;
}

The return value from create_int_array should be saved in an int * ptr. In the example it is being saved in arr_ptr which is a void * causing the int * typing to be removed. the c language does not provide a mechanism for remembering what type a variable was cast to in the past. All it knows is the type of reference currently being performed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM