I wanted to create a general print array function. This function would print array elements based on the data type.
#include "utilities.h"
//type : 0 ->int
// : 1->char
void print_array(void *arr, int length, int type){
int i = 0;
for(i=0;i<length;i++){
switch(type) {
case 0:
printf("Integer %d %d\n", (int*)(arr+i));
break;
case 1:
printf("%c \n", (char*)(arr+i));
break;
case 2:
printf("%s \n", (char*)(arr+i));
break;
case 3:
printf("%x \n", (int*)(arr+i));
break;
default:
printf("Format not supported yet. %d \n",type);
return;
}
}
}
void test_print_array(){
int int_arr[3] = {0,1,2};
print_array(int_arr,3,0);
}
int main(){
test_print_array();
return 0;
}
Output I am getting is
Integer -486474964
Integer -486474963
Integer -486474962
Instead of 0,1,2
I also tried using arr[i] instead of (int*)(arr+i) but I am getting compiler errors on that.
printf("%c \n", (char*)(arr+i));.%cexpect a char` orint, not a pointer.((int *)arr)[i]instead of(int*)(arr+i)void*, like gcc. Those that do, consider the distance between "elements" to be 1.