Home > Enterprise >  C type won't be recognized properly
C type won't be recognized properly

Time:02-24

I have an error when I compile my C program.

I have this code :

#include <stdio.h>
#include <stdlib.h>
#define SET__SIZE 10
#define SET__BOUND ((void*) NULL)

struct set {
  void *s[SET__SIZE];
  int cursor;
  int (*cmp)(const void*, const void*);
  void * (*copy)(const void*);
  void (*del)(void *);
};

int find(const void *s[], void *c, int (*cmp)(const void*, const void*))
{
  int i = 0;
  while (s[i]!=SET__BOUND && cmp(s[i],c)<0)
    i  ;
  return i;
}

int set__find(const struct set *se, void *c)
{
  return (se->cmp(se->s[find(se->s,c,se->cmp)],c)==0);
}

For some reason, gcc is raising a warning for the find call in set__find saying :

note: expected ‘const void **’ but argument is of type ‘void * const*’

I can't understand why he thinks the argument is a constant pointer (if I understood the error right)

CodePudding user response:

As I tried, the note goes away, when I change the code to

struct set {
  void *s[SET__SIZE];
  int cursor;
  int (*cmp)(const void*, const void*);
  void * (*copy)(const void*);
  void (*del)(void *);
};

int find(void * const s[], void *c, int (*cmp)(const void*, const void*))
{
  int i = 0;
  while (s[i]!=SET__BOUND && cmp(s[i],c)<0)
    i  ;
  return i;
}

int set__find(const struct set *se, void *c)
{
  return (se->cmp(se->s[find(se->s,c,se->cmp)],c)==0);
}

Explanation

In the answer... No point of writting it again.

CodePudding user response:

why he thinks the argument is a constant pointer

struct set {
   void *s[SET__SIZE];

The structure set contains the array s.

const struct set *se

se points to a constant structure set. Because the structure is constant, the memory for the structure is constant. The elements of the array s can't be modified, they are in constant memory.

find(se->s, 

Arrays decay to the pointer to the first element. So imagine it's TYPE s[SET__SIZE] where TYPE is a void*. TYPE s[SET__SIZE] decays to a pointer TYPE *. But, it's constant, so it's const TYPE s[SET__SIZE]. So it decays to a const TYPE *. You can't modify it, it's a constant array. TYPE is a void* - you can dereference the element and modify it then, but you can't modify the pointer value itself.

TL;DR you want int find(void * const s[] as in the other answer.

  • Related