Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't function access generic parameter
    primarykey
    data
    text
    <p>I am slowly learning how to program generic functions in C and get into trouble now and so often. I am making a program that makes a union of two arrays, in this implementation two int arrays. The first problem, which also leads to the second one, is that the compareints (function) does not access one of the passed arguments (void *): I can't figure out why? I been staring at the screen for to long time now...</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; //makes union of two generic arrays and eliminates duplicates if there are some... void ** unite(int (*comp)(void *f, void *s), void **first, void **second, int f_size, int s_size, int bytes, int *x) { int i; void **arr=malloc(bytes*(f_size+s_size)); for(i=0; i&lt;f_size+s_size; i++) { /* first bigger */ if(((*comp)(*first, *second))&gt;0) { *(arr+i)=*(first++); } /* second bigger */ else if(((*comp)(*first, *second))&lt;0) { *(arr+i)=*((second++)); } /* equal =&gt; just one copy */ else { *(arr+i)=*(first++); second++; } } *x=i; return arr; } int compareints(void *first, void *second) { if(*((int *)first)&gt;*((int *)second)) //can't access the memoryloc in second... return 1; else if(*((int *)first)&lt;*((int *)second)) return -1; else return 0; } int main(int argc, const char * argv[]) { int arr[10]={1, 2, 4, 12, 22, 29, 33, 77, 98}; int arr2[5]={3, 5, 7, 8, 9}; void **first=malloc(sizeof(int *)*10); void **second=malloc(sizeof(int *)*5); //make pointers to static arrays in dynamic arrays int f_ind, s_ind; for(f_ind=0; f_ind&lt;10; f_ind++) first[f_ind]=&amp;arr[f_ind]; for(s_ind=0; s_ind&lt;5; s_ind++) second[s_ind]=&amp;arr2[s_ind]; int i; //make union of the two arrays and print out the result void **ret=unite(&amp;compareints, first, second, 10, 5, sizeof(int), &amp;i); for(int k=0; k&lt;i; k++) printf("%d ", *((int *)ret[k])); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload