Man Dang
Man Dang

Reputation: 21

C language - pointer arithmetic

The functions should use pointer arithmetic (instead of array subscripting). In other words, eliminate the loop index variables and all use of the [] operator in the functions.

void set_complement(int *a, int n, int *complement)
    {
        //pointers and variables declaration
        int i;
        int *Pa = a;
        int *Pc = complement;

        for(i = 0; i < n; i++)
            {
                if( *(Pa + i) == 0)
                    {
                        *(Pc + i) = 1;
                    }
            }
    }

My question is: Am I using pointer arithmetic in the for-loop?

Upvotes: 2

Views: 479

Answers (3)

user5063151
user5063151

Reputation:

Yes, essentially, the indexing notation is a shorthand for pointer arithmetic. By default, the variable int *a points to the first index in that array. Technically, int *a is just a pointer to an integer, and you just 'happen to know' that other integers in memory follow it. And thus they have given us a convenient notation

a[i] // where i is the number of spaces passed point *a we want to look.

I am not sure what you are trying to do within the loop, but to access the ith element, you would do the following. My function just takes the compliment of the array a. nothing is done to c.

#include <stdio.h>

void set_compliment(int *a, int *compliment, int n) {
  int i;

  for (i = 0; i < n; i++) {

   // if (a[i] == 0)
   if ( *(a + i) == 0) {

     // a[i] = 1;
     *(a + i) = 1;

     // else if (a[i] == 1)
   } else if ( *(a+i) == 1) {

     // a[i] = 0;
     *(a + i) = 0;
   }
  }
}

//------------------------------------------------------------------------------

void display(int *a, int n) {
  int i;

  for (i = 0; i < n; i++) {
    printf("%i ", a[i]);
  }

  printf("\n");
}

//------------------------------------------------------------------------------

int main() {

  int a[] = {1, 1, 1, 1, 0};
  int c[] = {0, 0, 0, 0, 1};

  // Get length of array
  int n = sizeof(a) / sizeof(a[0]);

  set_compliment(a, c, n);

  display(a, n);
  display(c, n);

  return 0;
}

Upvotes: 0

Mateusz Drost
Mateusz Drost

Reputation: 1191

Yes, you are using pointer arithmetic. But you not eliminated loop index variable so you could write something like:

void set_complement(int *a, int n, int *complement)
{
    //pointers declaration
    int *Pa = a;
    int *Pc = complement;
    int *Pend = a + n;

    for (; Pa != Pend; ++Pa, ++Pc)
    {
        if(*Pa == 0)
        {
            *Pc = 1;
        }
    }
}

Upvotes: 1

Mureinik
Mureinik

Reputation: 311188

In a word - yes. By adding ints to pointers you're effectively moving the pointer (and then dereferencing it), or, in other words - you are performing pointer arithmetic.

Upvotes: 1

Related Questions