2

I am a newcomer to the world of C. I am self-teaching and would appreciate some help with a couple of questions.

This program is a simplified variation on one written in this example to demonstrate the use of pointers with arrays of structs. The things I'm having trouble getting my head around are:

  1. How the array is incremented in the first for loop. The ++ operator is used directly on the array of structs whereas I would have expected the need to do something more like in_p[i] inside the loop (with i being an int that get incremented).
  2. The way that the comparison is being made in this loop. I didn't think that in_p < &ar[ARSIZE] would be possible since both are of type struct wp_char. What is actually being compared here?

Both the example in the book and my example compile and run.

Thank you.

#include <stdio.h>
#include <stdlib.h>

#define ARSIZE 5

struct wp_char{
      char wp_cval;
      short wp_font;
      short wp_psize;
}ar[ARSIZE];

void infun(struct wp_char *, char cval, int font, int psize);

int main(void)
{
    struct wp_char wp_tmp, *lo_indx, *hi_indx, *in_p;
    char c[] = {'a','b','c','d','e'};
    int i1[] = {2,3,4,5,6};
    int i2[] = {7,8,9,10,11};
    int i = 0;

    for(in_p = ar; in_p < &ar[ARSIZE]; in_p++){
        infun(in_p, c[i], i1[i], i2[i]);
        i++;
    }

    int j;

    for(j=0;j<ARSIZE;j++)
    {
        printf("%c\n",c[j]);
        printf("%d\n",i1[j]);
        printf("%d\n",i2[j]);
        puts("\n");
    }

    exit(0);
}

void infun( struct wp_char *inp, char cval, int font, int psize)
{
`
      inp->wp_cval = cval;
      inp->wp_font = font;
      inp->wp_psize = psize;

      return;
}
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
MrCrinkle
  • 621
  • 1
  • 5
  • 6

1 Answers1

3

Question 1:

In C pointer arithmetic, ++ and -- increment and decrement a pointer by the size of the thing being pointed to, not by a byte (or some other aribitrary measure). See e.g. http://www.eskimo.com/~scs/cclass/notes/sx10b.html and http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html.

Note that this also applies to plain old addition and subtraction too:

float x[10];
float xPtr = &x[0];  // OR could write simply "float xPtr = x;"

xPtr = xPtr + 1; // xPtr now points at x[1]
xPtr = xPtr - 1; // xPtr now points at x[0] again
xPtr = xPtr + 9; // xPtr now points at last item in the array, x[9]

Question 2:

They're not of type struct wp_char, they're of type struct wp_char*, i.e. pointer to that struct. Think of them as a number pointing to a memory location containing one of those structs. You can compare two memory location for equality.

occulus
  • 16,959
  • 6
  • 53
  • 76