I hope you can help me! I added this function to my array.c to shuffle the array elements and it works with static Item *a; static int dim; in my array.c.
static Item *a;
static int dim = 3;
a=malloc( dim * sizeof(Item);
void random_array() {
int i , j;
Item t;
for (i = dim - 1;i > 0; i--)
{
j = rand() % (i + 1);
t = a[i];
a[i] = a[j];
a[j] = t;
//swap(a[i], a[j]);
}
}
item.h
typedef void *Item;
item-int.c
#include <stdio.h>
#include <stdlib.h>
#include "item.h"
Item inputItem(){
int *p;
p=malloc(sizeof(int));
scanf("%d",p);
return p;
}
void outputItem(Item item){
int *p;
p=item;
printf("%d ",*p);
}
int cmpItem(Item item1,Item item2){
int *p1,*p2;
p1 = item1;
p2 = item2;
return *p1 - *p2;
}
So I tried with a function swap (a[i], a[j]) from the file utils.c but it doesn't work.
void swap (Item pa, Item pb) {
Item t;
t = pa;
pa = pb;
pb = t;
}
It works with these instructions:
void swap (Item *pa, Item *pb)
{
Item t;
t = *pa;
*pa = *pb;
*pb = t;
}
I know that with "typedef void *Item' Item t is like void *t and Item *a is like void **a, right? So with double pointers I have a dynamic array with many pointers thanks to a=malloc(numberelements*(sizeof(Item)); and with a[i]=malloc(sizeof(Item) every pointer points to a memory location with many bytes?
So for t I don't need malloc because with t = a[i] t points to memory location pointed from a[i], right? If yes, why do I have to use in my swap function t = *pa etc. instead of t = pa ? I have several doubts about double pointers as function parameters. I hope you can resolve that. Thanks in advance!
&
. And yes, this will work with pointers if that is whatItem
really is. – Michael Dorganvoid swap(int *pa, int *pb)
function first, and make sure you understand what it does and how to use it. Trying to do it withvoid *
from the start only obfuscates the simpler things. – dxiv