Home > Net >  Casting generic pointers in c
Casting generic pointers in c

Time:11-21

I found this code in a book, trying to explain how generic pointers works using this to copy one matrix to another one.

#include <stdio.h>

#define FILAS 2
#define COLS 3

void copiarMatrices(void *, void *, int);

int main(){

    int m1[FILAS][COLS] = {24, 30, 15, 45, 34, 7};
    int m2[FILAS][COLS];

    copiarMatrices(m2, m1, sizeof(m1));

    for (int i = 0; i < FILAS; i  ){
        for (int j = 0; j < COLS; j  ) printf("%d ", m2[i][j]);
        printf("\n");
    }
}

void copiarMatrices(void *dest, void *orig, int n){
    char *destino = (char *)dest;
    char *origen = (char *)orig;

    for (int i = 0; i < n; i  ) {
        destino[i] = origen[i];
    }
}

The book said that the only data type that we could cast the void pointers was char because other data types are not allowed because of the bytes size.

I don't understand this and also if I execute the program with either int or double data type on void pointers the program get stuck for a few seconds and then finish well.

CodePudding user response:

What the book is saying is that the result of the "sizeof" operator is the expression argument's size in bytes. If instead you were to specify "sizeof(m1) / sizeof(int)" then instead of "char *" you would need to cast the parameters to "int *" because you would then be passing the number of ints to copy instead of the number of bytes.

CodePudding user response:

Function copiarMatrices copies buffer of any size. Let's imagine that buffer orig is 5 bytes. If you cast to int * inside copiarMatrices and int is 4 bytes and I want to copy all 5 bytes from orig to dest than n will not be integer (if n=1 than 4 bytes will be copied, if n=2 than 8 bytes will be copied but I need to copy 5 bytes). So, we can agree that copying will be by bytes and n means number of bytes which will be copied. In general you have to call copiarMatrices(m2, m1, FILAS * COLS * sizeof(int));

CodePudding user response:

You do not need any special functions. You function copiarMatrices can be reduced to memcpy(m2, m1, sizeof(m1));

Some remarks.

  1. Do not use int for sizes. Use the correct size_t type instead.
  2. Try to be const correct.
  3. Return a reference to the destination object, It will allow the function to be used in the expressions.

Your function prototype should be: void *copiarMatrices(void *, const void *, const size_t);. If you want to make the compiler life easier you may: void *copiarMatrices(void restrict *, const void * restrict, const size_t);

  • Related