In my routine I need "grow" an array by expanding and adding a new item at the end. This add2arr routine handles different type of data, for this reason I code the parameter as void. The code works but compiler shows warning, which makes my assumption about void type questionable.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int add2arr(void **arr, void *item, int sz, int *cnt)
{
const int newsz = sz * (*cnt + 1);
const int offset = sz * (*cnt);
if(*cnt == 0)
*arr = malloc(sz);
else
*arr = realloc(*arr, newsz);
if(*arr == NULL)
return(-1);
memcpy(*arr + offset, item, sz);
*cnt = *cnt + 1;
return(0);
}
typedef struct _STR {
int n;
float f;
double d;
char s[20];
} STR;
int main(int argc, char *argv[])
{
const int cnt = (argc == 2) ? atoi(argv[1]) : 10;
int n;
STR item;
STR *str = NULL;
int scnt = 0;
for(n = 0; n < cnt; n++)
{
item.n = n; item.f = n * 1.1; item.d = n *10.1;
sprintf(item.s, "%i:%.1f:%.2f", item.n, item.f, item.d);
if(add2arr(&str, &item, sizeof(item), &scnt) == -1)
{
printf("Abort\n");
return(1);
}
}
for(n = 0; n < cnt; n++)
{
printf("%6i %8.2f %10.2f %s\n",
str[n].n, str[n].f, str[n].d, str[n].s);
}
return(0);
}
Compile warnings are:
Code:
cc -c c.c
c.c: In function ‘main’:
c.c:42:14: warning: passing argument 1 of ‘add2arr’ from incompatible pointer type [-Wincompatible-pointer-types]
42 | if(add2arr(&str, &item, sizeof(item), &scnt) == -1)
| ^~~~
| |
| STR ** {aka struct _STR **}
c.c:5:20: note: expected ‘void **’ but argument is of type ‘STR **’ {aka ‘struct _STR **’}
5 | int add2arr(void **arr, void *item, int sz, int *cnt)
| ~~~~~~~^~~
My compiler is:
Code:
cc --version
cc (Ubuntu 9.3.0-10ubuntu2) 9.3.0
How should I code patameters in my add2arr so compiler is not complaining?
Just a note - when I compile under Solaris 11 / GCC 4.5.2 there are no warnings.