Hello I have a question for you and I hope you can help me! I write here only the instructions for add 3 elements in a double pointer using item.h. So when I write "Item *a" is like void **a, right?
Anyway the program works if I use malloc with dim=20 without realloc when I use output_array, but if I wanna start with dim=3 and after every insert_element I use realloc with dim+1 I get segmentation fault when I use output_array.
With inselem_array(a,&dim); in my main I edit my "Item *a" using function? I thought this is like call by reference, so any change made to the reference pointer will effect the original pointer.
When I have double pointer, is it like dynamic array with Item (alias void) pointers to other void pointers, right?
I need your help! Can you help me please? Thanks in advance!
I write 1 for start an array. I enter 1,2 and 3. After I write 3 for insert 4 in position a[1] for get 1,4,2,3 but I get segmentation fault and crash...
main.c
Code:
#include "array.h"
#include "item.h"
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int dim = 3;
Item *a;
int scelta = 0, b = 0;
printf("1 - Insert elements in an array\n");
printf("3 - Insert new element\n");
printf("7 - Output array\n");
printf("-1 - Exit");
do {
printf("\nWrite your choice\n");
scanf("%d", &scelta);
switch (scelta) {
case 1:
a = malloc(dim * sizeof(Item));
input_array(a, dim);
b = 1;
break;
case 3:
inselem_array(a, &dim);
break;
case 7:
output_array(a, dim);
break;
default:
if (scelta != -1)
printf("Wrong choice\n");
break;
}
} while (scelta != -1);
return 0;
}
array.h
Code:
#include "item.h"
void input_array (Item *, int );
void free_array();
void inselem_array (Item *, int *);
void output_array (Item [], int );
array.c
Code:
#include "array.h"
#include "item.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
void input_array(Item *a, int n) {
int i;
for (i = 0; i < n; i++) {
printf("Insert element number %d\n", i + 1);
a[i] = inputItem();
}
}
void free_array(Item *a) { free(a); }
void output_array(Item *a, int n) {
int i;
for (i = 0; i < n; i++)
outputItem(a[i]);
}
void inselem_array(Item *a, int *n) {
int i, pos;
Item item;
printf("Insert new element\n");
item = (inputItem());
printf("Insert position for new element\n");
scanf("%d", &pos);
if (pos <= *n) {
*n = *n + 1;
a = realloc(a, *n * sizeof(Item));
i = *n - 1;
while (i > pos) {
a[i] = a[i - 1];
i--;
}
a[i] = item;
} else
printf("Wrong position\n");
}
item.h
Code:
typedef void *Item;
Item inputItem();
void outputItem(Item);
int cmpItem(Item,Item);
item-int.c
Code:
#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;
}