1

Hey guys I am currently learning DSA and in ADT I have a problem: This is a code that creates a custom array and takes the input of the array and stores it and prints it too but I want to ask that what does that [i] do in printf("%d\n",(a->ptr)[i]); that thing is what I am not getting in this code

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

struct myArray{
    int total_size;
    int used_size;
    int *ptr;
};

void createArray(struct myArray * a,int tSize,int uSize)
{
    a->total_size = tSize;
    a->used_size = uSize;
    a->ptr = (int *) malloc(tSize * sizeof(int));
}

void show(struct myArray * a){
    for(int i=0; i < a->used_size; i++){
        printf("%d\n",(a->ptr)[i]);
    }
}

void setVal(struct myArray * a){
    int n;
    for(int i=0; i < a->used_size; i++){
        printf("Enter Element %d: ", i);
        scanf("%d",&n);
        (a->ptr)[i] = n;
    }
}

int main(){
    struct myArray marks;
    createArray(&marks,10,2);
    printf("We are running setVal now\n");
    setVal(&marks);

    printf("We are running show now\n");
    show(&marks);
    return 0;
}
user438383
  • 5,716
  • 8
  • 28
  • 43
  • `a->ptr` is a pointer, and `[i]` is dereferencing like array – qrsngky Aug 04 '22 at 09:03
  • can you explain in detail about [i] – Shresth Gour Aug 04 '22 at 09:04
  • Could you please be more precise? As this is addressed in each basic C tutorial, it would be useful to know what specifically is unclear for you. – Gerhardh Aug 04 '22 at 09:06
  • 1
    In C, `a[b]` is equivalent to `*(a+b)`. If `a` is a pointer and `b` is an integer, it does pointer addition, then dereferences the resulting pointer. In your case, `(a->ptr)[i]` is equivalent to first assigning `tmp = a->ptr;` then using `tmp[i]`. This is just basic array/pointer indexing. – Tom Karzes Aug 04 '22 at 09:07
  • Before learning DSA in C, you should first understand basic C. I suggest you go find a good introductory book on C. – Victor Aug 04 '22 at 09:11
  • 1
    What is DSA in your context? – Gerhardh Aug 04 '22 at 09:12

1 Answers1

3

The data member ptr points to a dynamically allocated array

a->ptr = (int *) malloc(tSize * sizeof(int));

To access elements of the array you can use the subscript operator

 printf("%d\n",(a->ptr)[i]);

To make it more clear consider the following code snippet.

enum { N = 10 };
int *ptr = malloc( N * sizeof( int ) );
for ( int i = 0; i < N; i++ )
{
    ptr[i] = i;
}

The difference with the original code is the pointer ptr is a data member of a structure and to access ptr using a pointer to an object of the structure type you have to change in the code above the expression

ptr[i]

to

( a->ptr )[i]

that is the same as

a->ptr[i]

because there are used the postfix operator -> and [] that evaluates left to right.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335