Search code examples
cc89ansi-c

Adding a pointer to size_t in C89


First, I know about this thread:

Now Assume I have this array:

size_t    count = some_value();
struct info    *pinfos = malloc(count * sizeof(struct info));

and I wanted to "navigate" it using the variable

struct info     *p;

Can I use this code to check the limit?

p   <   (char*)pinfos  +  count*sizeof(struct info)  -  1

Is this legal in C89?

Is there a more "appropriate" way to do so?


Solution

  • You can do that indeed but you are overcomplicating it, just do

    p < pinfos + count - 1
    

    and it will work because pointer arithmetic is performed in terms of the size of the pointer type.