Home > Software design >  If e is a pointer then why . operator is being used instead of ->?
If e is a pointer then why . operator is being used instead of ->?

Time:09-11

Code works fine. Output received from some input In several places after the term e[something] '.' operator is used. Since e is a pointer that holds address to an element, Why isn't '->' operator is used. Is it so because e[something] will hold an entire structure as value to that index=something instead of an address to the element?

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

struct element{
  int i;
  int j;
  int x;  //x represents value of A[i][j]
};

struct sparse{
  int m;
  int n;
  int num;  // num represents no. of non-zero elements
  struct element *e;
};

void create(struct sparse *);
void display(struct sparse);

void create(struct sparse *s){
  printf("Enter Dimensions :\n");
  scanf("%d%d", &s->m, &s->n);
  printf("Enter number of non-zero elements :");
  scanf("%d", &s->num);

  s->e = (struct element *) malloc(s->num * sizeof(struct element));

  printf("Enter i, j, x :\n");
  for(int k = 0; k < s->num; k  ){
    scanf("%d%d%d", &s->e[k].i, &s->e[k].j, &s->e[k].x); // why not s->e[k]->i
  }
}

void display(struct sparse s){
  int p, q, k = 0;
  for(p = 0; p < s.m; p  ){
    for(q = 0; q < s.n; q  ){
      if(p == s.e[k].i && q == s.e[k].j){
        printf("%d ", s.e[k].x);
        k  ;
      }
      else{
        printf("0 ");
      }
    }
    printf("\n");
  }
}

int main(){
  struct sparse s;

  create(&s);
  display(s);
  return 0;
}

CodePudding user response:

back to basics of arrays :

arr[i] is equivalent to *(arr i) and arr itself is the base address of the array

so e[k] is equivalent to *(e k) and e value itself is just address.

so when you say *(e k) this means that you have the actual instance not a pointer that points to its place. as you dereference e using [] operator.

the only case that you can write e[k]->i; is when e[k] itself is a pointer but in your case e[k] isn't a pointer , as said above , it's equivalent to *(e k) so it's dereferenced and *(address) will give you the actual instance in the memory that e k points to.

CodePudding user response:

s->e = (struct element *) malloc(s->num * sizeof(struct element)); 

e points to an array of structs.

doing something like s->e[i].member is completely legal. We can use . because e[i] isn't pointer.

So if it isn't a pointer what is it?

e[i] is some value/data at an address. Specifically e[i] is some value/data at the address of the ith struct in e. Using e[i] will allow us to reference the ith struct.

When we do e[i] it's the same as *(e i). Notice how a * (dereference operator) is used. This will get us the value/data that we need from the address that e i points to, which in turn will enable us to access its members.

  • Related